I was trying to use SSH tunneling to access my MySQL database using C# but I'm getting an exception
Unable to connect to any of the specified MySQL hosts.
I got this code with the help of this:
C# SSH tunnel to MySQL server
Here is my code:
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("example.com", 2222, "username", "password");
connectionInfo.Timeout = TimeSpan.FromSeconds(30);
using (var client = new SshClient(connectionInfo))
{
try
{
Console.WriteLine("Trying SSH connection...");
client.Connect();
if (client.IsConnected)
{
Console.WriteLine("SSH connection is active: {0}", client.ConnectionInfo.ToString());
}
else
{
Console.WriteLine("SSH connection has failed: {0}", client.ConnectionInfo.ToString());
}
Console.WriteLine("\r\nTrying port forwarding...");
var portFwld = new ForwardedPortLocal(IPAddress.Loopback.ToString(),2222, "example.com", 3306);
client.AddForwardedPort(portFwld);
portFwld.Start();
if (portFwld.IsStarted)
{
Console.WriteLine("Port forwarded: {0}", portFwld.ToString());
Console.WriteLine("\r\nTrying database connection...");
DBConnect dbConnect = new DBConnect("127.0.0.1", "database", "username", "password", "3306");
int id = dbConnect.Count("table");
MessageBox.Show(id + " count ");
}
else
{
Console.WriteLine("Port forwarding has failed.");
}
}
catch (SshException ex)
{
Console.WriteLine("SSH client connection error: {0}", ex.Message);
}
catch (System.Net.Sockets.SocketException ex1)
{
Console.WriteLine("Socket connection error: {0}", ex1.Message);
}
}
private MySqlConnection connection;
private string server;
public string Server
{
get
{
return this.server;
}
set
{
this.server = value;
}
}
private string database;
public string Database
{
get
{
return this.database;
}
set
{
this.database = value;
}
}
private string uid;
public string Uid
{
get
{
return this.server;
}
set
{
this.server = value;
}
}
private string password;
public string Password
{
get
{
return this.password;
}
set
{
this.password = value;
}
}
private string port;
public string Port
{
get
{
return this.port;
}
set
{
this.port = value;
}
}
//Constructor
public DBConnect(string server, string database, string uid, string password, string port = "3306")
{
this.server = server;
this.database = database;
this.uid = uid;
this.password = password;
this.port = port;
Initialize();
}
//Initialize values
private void Initialize()
{
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
Console.WriteLine("MySQL connected.");
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
Console.WriteLine("Cannot connect to server. Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
default:
Console.WriteLine("Unhandled exception: {0}.", ex.Message);
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
//Count statement
public int Count(string tableName)
{
string query = "SELECT Count(*) FROM " + tableName;
int Count = -1;
//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar() + "");
//close Connection
this.CloseConnection();
return Count;
}
return Count;
}
The output that I got in my console is:
Trying SSH connection...
A first chance exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
SSH connection is active: Renci.SshNet.PasswordConnectionInfo
Trying port forwarding...
Port forwarded: Renci.SshNet.ForwardedPortLocal
A first chance exception of type 'Renci.SshNet.Common.SshConnectionException' occurred in Renci.SshNet.dll
Trying database connection...
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Error: 0 : Unable to connect to any of the specified MySQL hosts.
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Unhandled exception: Unable to connect to any of the specified MySQL hosts..
UPATE:
I have changed the port forwarding settings to :
var portFwld = new ForwardedPortLocal("127.0.0.1", 1000, "127.0.0.1", 3306);
and I have changed my mySQL String to :
connectionString = "server=127.0.0.1;port=1000; UID=username; password=password; database=data1; charset=utf8;Allow User Variables=True";
I'm being connected to the ssh and my port is forwarded but I still can't connect to MySQL database, I'm getting an exception:
A first chance exception of type 'System.IO.EndOfStreamException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Error: 0 : Reading from the stream has failed.
You have to connect the MySQL to the bound port of the forwarding. I.e. to the 2222.
Or even more semantically correct, use portFwld.BoundPort. Equivalently, use portFwld.BoundHost.
DBConnect dbConnect = new DBConnect(portFwld.BoundHost, "database", "username", "password", portFwld.BoundPort);
Also note that it makes more sense to refer to the MySQL host as "localhost", rather than the "example.com", as the hostname is resolved on the server-side. And when on the server side, you typically won't connect to "example.com", but to a "localhost".
var portFwld = new ForwardedPortLocal(IPAddress.Loopback.ToString(), 2222, "localhost", 3306);
And of course you need to keep the SSH session open while you need the tunnel. So you have to connect to the DB within the using block:
using (var client = new SshClient(connectionInfo))
{
...
client.Connect();
...
portFwld.Start();
...
DBConnect dbConnect = new DBConnect(portFwld.BoundHost, "database", "username", "password", portFwld.BoundPort);
}
Related
I have read the Mirosoft Document.When we open a connection and then close it, it is possible to use the session.
I have written this block of code to run a command but I get an error message, which says there is no connection. Do you have any Idee how can I close the connection, but use the session to run a cammand:
try
{
using (AdomdConnection adomdConnection = new AdomdConnection("MY Connection String"))
{
adomdConnection.Open();
adomdConnection.Close(false);
while (true)
{
String query = #"EVALUATE { BLANK()}";
AdomdCommand adomdCommand = new AdomdCommand(query);
Console.WriteLine(adomdConnection.SessionID.ToString() + " " + DateTime.Now.ToString());
AdomdDataReader reader = adomdCommand.ExecuteReader();
reader.Close();
System.Threading.Thread.Sleep(30000);
}
}
}
catch(AdomdConnectionException ex)
{
Console.WriteLine(ex.Message.ToString());
}
In the examples shown in the document you list, it has:
/*First, try to connect to the specified data source.
If the connection string is not valid, or if the specified
provider does not support sessions, an exception is thrown. */
objConnection.ConnectionString = connectionString;
objConnection.Open();
// Now that the connection is open, retrieve the new
// active session ID.
strSessionID = objConnection.SessionID;
// Close the connection, but leave the session open.
objConnection.Close(false);
return strSessionID;
And in your code specifically, you have:
adomdConnection.Open();
adomdConnection.Close(false);
while (true)
{
String query = #"EVALUATE { BLANK()}";
AdomdCommand adomdCommand = new AdomdCommand(query);
Console.WriteLine(adomdConnection.SessionID.ToString() + " " +
DateTime.Now.ToString());
AdomdDataReader reader = adomdCommand.ExecuteReader();
reader.Close();
System.Threading.Thread.Sleep(30000);
}
Wouldn't you want to have this instead (based on the example given)?
adomdConnection.Open();
while (true)
{
String query = #"EVALUATE { BLANK()}";
AdomdCommand adomdCommand = new AdomdCommand(query);
Console.WriteLine(adomdConnection.SessionID.ToString() + " " +
DateTime.Now.ToString());
AdomdDataReader reader = adomdCommand.ExecuteReader();
reader.Close();
System.Threading.Thread.Sleep(30000);
}
adomdConnection.Close(false);
It seems as though it's complaining because you're closing the connection before you even use it, according to the order in which your code looks to be operating. Try moving the adomdConnection.Close(false); after your while loop.
I am developing a WebService in C # however I am facing an error.
This is the error :
System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The message or signature supplied for verification has been altered
So I sometimes get this error when I open my MySQL connection in my WebService.
I had this error by launching my webService twice at the same time then I tried again and no more errors.
My web service is on a Windows server 2012 R2 and i'm using .NET Framework 4.7.2 (It is called by the website php).
I did quite a bit of internet research and came across this in C# :
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
But it doesn't work, Do you have any idea so that I do not face this problem again ?
There is my MySQL open connection method :
public MySqlConnection OpenConnectionDB(string clientId)
{
listVerifs = new List<string>();
int iConn = 0;
try
{
MySqlConnection sqlCo = new MySqlConnection("server=MyServer;database=" + this.db + ";username=MyUID;password=MyPwd;AllowLoadLocalInfile=true");
if (sqlCo.State != ConnectionState.Open)
{
sqlCo.Open();
}
listVerifs.Add("CO SQL");
dataSourceDBF = #"//ntserver/Winbooks_Data/winbooks/data/" + clientId + "/";
dbfCo = new AdsConnection(#"data Source=//ntserver/Winbooks_Data/winbooks/data/" + clientId + "/" + clientId + ".add;User ID=mYUID;Password=;ServerType=local;ReadOnly=true;pooling=true;TrimTrailingSpaces=true;TableType=CDX;LockMode=COMPATIBLE");
if (dbfCo.State == ConnectionState.Closed)
{
dbfCo.Open();
}
listVerifs.Add("CO DBF");
Console.WriteLine("Databases connections open succesfull");
return sqlCo;
}
catch (Exception e)
{
dbfCo = null;
Console.WriteLine("Error connection " + e.Message);
test = e.Message;
log.AddLog("Erreur Fonction OpenConnectionDB : " + e.ToString(), 3, "WebServiceMySQL");
return null;
}
Thank's in advance !
I have a webapp, VS2013, C# and ASP.NET, and I use Oracle 12c as DB, so when I try to connect to DB from my webapp I got this error: ORA-12541: TNS:no listener, this is my code:
public bool OpenConnection(Label lbl)
{
try
{
using (cn = new OracleConnection(WebConfigurationManager.ConnectionStrings["RegistroConnection"].ToString()))
{
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
}
return true;
}
catch (NullReferenceException nullExcept)
{
lbl.Text = "Caught error: ." + nullExcept.ToString();
return false;
}
catch (OracleException dbEx)
{
lbl.Text = "OraException - " + dbEx.Message;
return false;
}
catch (Exception ex)
{
Exception current;
current = ex;
while (current != null)
{
current = current.InnerException;
}
lbl.Text = "Db base exception - " + ex.GetBaseException().ToString();
return false;
}
}
I have the connectionstring on my webconfig:
<connectionStrings>
<add name="RegistroConnection"
connectionString="Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =myServer)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SID = sidname)));User Id=user;Password=password;"
providerName="Oracle.DataAccess.Client"/>
</connectionStrings>
the dll already added is:
- Oracle.DataAccess.Client
If I try to connect through Sql Developer I have a successful connection but on my webapp I have this error: ORA-12541: TNS:no listener
I am building an application which has a database on the server machine and I am using this method for database access:
public static string GetDefaultConnectionString()
{
//get my db info from ini file
dbinfo DatabaseInfo = new dbinfo();
DatabaseInfo = GetDatabaseInfo();
if (DatabaseInfo.dbName == "" || DatabaseInfo.Password == "" || DatabaseInfo.Server == "" || DatabaseInfo.UserId == "")
{
throw new Exception("Database config file is not valid");
}
else
{
MessageBox.Show("Db name " + DatabaseInfo.dbName);
MessageBox.Show("User " + DatabaseInfo.UserId);
MessageBox.Show("Db Pass " + DatabaseInfo.Password);
MessageBox.Show("Db Server " + DatabaseInfo.Server);
}
string conStrIntegratedSecurity = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = "res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog = DatabaseInfo.dbName,
DataSource = DatabaseInfo.Server,
IntegratedSecurity = true,
UserID = DatabaseInfo.UserId,
Password = DatabaseInfo.Password,
MultipleActiveResultSets = true,
ConnectTimeout = 0,
MaxPoolSize = 500,
}.ConnectionString
}.ConnectionString;
//MessageBox.Show(conStrIntegratedSecurity);
return conStrIntegratedSecurity;
}
and it works fine in server pc.
But, when I install this application on any client machine, it cannot open a connection and it gives the following error message:
System.Data.EntityException: The underlying provider failed on Open. --->
System.Data.SqlClient.SqlException: Cannot open database "dbName" requested by the login. The login failed.
Login failed for user 'ServerName\User'.
Does anyone know why this is happening?
I just use
IntegratedSecurity = true,
to
IntegratedSecurity = false,
and it works!
I have the following code, just to test connection:
public void Test()
{
SqlCeConnection conn = new SqlCeConnection(#"Data Source=/Application/Database.sdf;");
try
{
conn.Open();
label1.text = "Connection!";
}
catch (Exception ee)
{
label1.text = "No connection!";
}
}
When trying to connect to this database, the application throws an exception at conn.Open() saying
SqlCeException was unhandled
and nothing more. The exception message is blank, so I'm having a hard time figuring out what went wrong.
The database file is there, and the application returns true with
File.Exist(#"/Application/Database.sdf");
so it does have access to the file.
I'm probably doing something really wrong here, can anyone help me out with this?
I'm using Compact Framework 2.0 on Windows CE 5, and the application in question is an existing one. I'm trying to add a database to it so I can load large amounts of data much more easier.
What Erik is saying is change your code to this:
public void Test()
{
SqlCeConnection conn = new SqlCeConnection(#"Data Source=/Application/Database.sdf;");
try
{
conn.Open();
label1.text = "Connection!";
}
catch (SqlCeException ee) // <- Notice the use of SqlCeException to read your errors
{
SqlCeErrorCollection errorCollection = ee.Errors;
StringBuilder bld = new StringBuilder();
Exception inner = ee.InnerException;
if (null != inner)
{
MessageBox.Show("Inner Exception: " + inner.ToString());
}
// Enumerate the errors to a message box.
foreach (SqlCeError err in errorCollection)
{
bld.Append("\n Error Code: " + err.HResult.ToString("X"));
bld.Append("\n Message : " + err.Message);
bld.Append("\n Minor Err.: " + err.NativeError);
bld.Append("\n Source : " + err.Source);
// Enumerate each numeric parameter for the error.
foreach (int numPar in err.NumericErrorParameters)
{
if (0 != numPar) bld.Append("\n Num. Par. : " + numPar);
}
// Enumerate each string parameter for the error.
foreach (string errPar in err.ErrorParameters)
{
if (String.Empty != errPar) bld.Append("\n Err. Par. : " + errPar);
}
}
label1.text = bld.ToString();
bld.Remove(0, bld.Length);
}
}
The generic Exception you are catching right now can not give you the details of the SqlCeException.