UWP to MariaDB using MySQL Connector Net 6.7.9 - c#

I've been trying to get some initial code working before I start working on my app.
I have had this working maybe a year ago so something tells me there is an update/version issue.
But any help is good so.
I have a raspberry pi set up with apache, MariaDB, php etc etc. I have a simple webpage running so apache is fine, I have another webpage that pulls data from a table so MariaDB is fine (fine-ish, given my issue). I have myphpadmin set up and can log in create new db's and users etc.
Now I would like to have a UWP app interact with a db hosted on my pi. I created a new user with SELECT and INSERT only for a specific db (hopefully this reduces security issues but I'm new so maybe I'm wishing).
I also then found the mariadb config file and commented the bind-address line. The skip-networking line is no longer in the file so just ignored that. (this is what the docs say to allow remote connections).
I have opened port 3306 on my router, and I also have a domain name and use no-ip but I assume this is all fine as apache runs fine. Saw someone talking about SSH, I changed my ssh port but I don't think that would be the issue.
Then the UWP.
Last time I tried this I had to use MySQL Connector Net 6.7.9 as newer versions didn't work with RT. So I have added this to the project references.
Now for simple testing the connection I have a button and TextBlock, click the button to attempt connecting and output the exception/result.
Have tried conn string builder as well as just a straight forward string, neither work.
private void ConnectDatabase_Click(object sender, RoutedEventArgs e)
{
string ConnString;
MySqlConnection Conn;
MySqlConnectionStringBuilder Csb = new MySqlConnectionStringBuilder();
Csb.Server = "http://rnd-domain.me";
Csb.Port = 3306;
Csb.UserID = "usr";
Csb.Password = "passwd";
Csb.Database = "testdb";
ConnString = "server=http://rnd-domain.me;database=testdb;uid=usr;pwd=passwd;";
Conn = new MySqlConnection(ConnString);
try
{
Conn.Open();
DbUpdateText.Text = "connected";
Conn.Close();
}
catch(Exception ex)
{
DbUpdateText.Text = ex.Message;
}
}
When I click the button the ex.Message is 'Unable to connect to any of the specified MySQL hosts.'.
There are no errors thrown with the app, just this unhelpful message.
I've googled this and wasted 80% of my sunday trying to get this working. I've added sslmode=none, charset=utf8, port=3306. I tried using server=localhost or using my current ip and even using my mariadb master user (not root).
What could be the issue?
Thanks.
Edit:
I just used the pi's internal IP and got a new ex.Message, understood this one about SSl, added sslmode=none and all is working.
So now its just getting around the domain name issue?

Your connection string isn't quite right.
You probably want this:
server=rnd-domain.me;database=testdb;uid=usr;pwd=REDACTED;
It doesn't make sense to mention http:// in a MySQL connection string, because the connection doesn't use the HTTP protocol. Rather it uses the MySQL protocol.

The issue was using a pc (client) and raspi (server) both inside the home network.
When I changed the host to the internal IP of the raspi it all worked fine.

Related

Can not connect to Sql database in C# asp mvc application with Entity Framework BUT the same code works with Winform application

First of all, please excuse me if it sounds too rooky. I consider myself novice in MVC applications.
I have ran into a strange problem and there does not seem to be any way out of this, at least so far..I have looked everywhere and left no stone unturned to get it worked. Finally I turned to this forum.
This is my first post, so any mistakes please overlook and guide me.
The problem is multifaceted...
The High Level Details...
I have created a C# ASP MVC Web Application waiting to be uploaded on a Remote Server (Client Machine)
The application uses Entity Framework - Code First approach
Connects to the database with Windows Authentication system
Scene1: Where the application worked
I have tested the application on my machine and it worked flawlessly.
I have Express edition of Sql Server Management Studio installed on my system.
Scene2: Where the application failed. The Problem - Big Picture
It works great on my system but while testing it on the Remote Server it crashes
The application fails to connect to the Remote Server Sql Database. As soon as it tries to connect to the database, it crashes with an error message "Login failed for user '<UserName>."
I have checked everything in the connection string - like -
Data source name is correct
Initial Catlog also points at the correct database name
Integrated Security = true
There is no UserID or password mentioned
Connection string worked great on my system. But it does work on the Client Machine and shows the error above.
Connection string is:
connectionString="Data Source=RemoteComputerName;Initial Catalog=DatabaseName;Integrated Security=True; MultipleActiveResultSets=true"
I am not able to figure out exactly what is causing the error - Is it my code or Is it the Sql Server database settings - permissions.
Since the connection worked on my local machine, which means the code is correct
In order to check whether sql server permissions are working..I have created partial 'test connection application' in WINFORM and uploaded on the Server, this time the code works and read all the table data.
but when I try to connect in MVC project it shows the error..."Login failed for user...".
I'm totally confused what works in WINFORM fails in MVC.
Database permissions must be right because when tried to access it using WINFORM it worked.
please let me know if I have missed to provide any details in this post.
Any help is highly appreciated!!!
Thank You.
Please show your connection string. (you can block out any real passwords, actual server names, actual db names).
Since you mention "Integrated Security = true"..........then you have to be aware of which Identity is running the process (the website or the winforms.exe)
When running as winforms app, you are running as "you" (most likely). As in, the logged in user to the windows o/s.
When running under IIS, you are running under the Identity associated with the App Pool you are using..which most likely is NOT you, but rather a service account.
Your service-account does not have access to the sql-server.
You can read in depth here: https://support.microsoft.com/en-us/help/4466942/understanding-identities-in-iis#:~:text=ApplicationPoolIdentity%3A%20When%20a%20new%20application,also%20a%20least%2Dprivileged%20account.
You can show this......by catching an exception, and then something like this:
You can replace ArithmeticException with whatever, I'm just showing "adding info" to a caught exception and rethrowing.
try
{
// some sql server access code
}
catch(Exception ex)
{
throw new ArithmeticException("What is the real IIdentity: " + this.FindIIdentity(), ex);
}
private string FindIIdentity()
{
try
{
//'Dim user As WindowsPrincipal = CType(System.Threading.Thread.CurrentPrincipal, WindowsPrincipal)
//'Dim ident As IIdentity = user.Identity
string returnValue = string.Empty;
WindowsIdentity ident = WindowsIdentity.GetCurrent();
returnValue = ident.Name;
try
{
returnValue += " on " + System.Environment.MachineName;
} catch (Exception ex)
{}
return returnValue;
} catch (Exception ex)
{
return "Error Finding Identity";
}
}
IIS screenshots

Unable connect to MySQL from C# but possible from other apps

I wanted to change MySQL server in my C# app. The app is run in my company and both - old and new MySQL servers are only accessible from the intranet. The problem is I can connect from HeidiSQL software and from python code but not from C#...
I have tried all possible solutions what I found, for ex. disabling firewall, using different packages from NuGet, modifying connection string, I created new console project only to paste various MySQL connection code - always with same error
Message: Unable to connect to any of the specified MySQL hosts.
Source: MySql.Data
Number: 1042
I', using .net Framework 4.5.2 (4.6.1 in my test project) and MySQL Server is '5.6.44-log - MySQL Community Server (GPL)'
One of C# connection code example that I have tested that is NOT working
using MySql.Data.MySqlClient;
public static MySqlConnection DB_connection;
DB_connection = new MySqlConnection(#"Server=MyIP;Database=myDB;Uid=my_user;Pwd=pass;");
try
{
DB_connection.Open();
isConn = true;
}
catch (...)
Working python code run from the same PC
import pymysql
import pprint
connection = pymysql.connect(host='MyIP',
user='my_user',
password='pass',
db='myDB')
try:
with connection.cursor() as cursor:
sql = "select * from table;"
cursor.execute(sql)
# connection.commit()
result = cursor.fetchall()
pprint.pprint(result)
finally:
connection.close()
Don't see anything wrong with your posted connection string but in case your's is a replicated scenario (I mean DB replication exists) then you will have to specify the replicated server IP/hostname as well like
Server=serverAddress1, serverAddress2, serverAddress3;Database=myDataBase;
Uid=myUsername;Pwd=myPassword;

.NET SQL Server connection issue - Maybe connection pool related

I am having a very strange problem and am hoping someone out there has had a similar experience.
My companies application for one client is getting "banned" from the SQL Server at the beginning of our application. The behavior is strange. I'll write it out in point form.
SQL Connections are created, data is retrieved, the connections are closed, talk to another datasource and then denied access to SQL Server.
Here's the long winded version:
.NET application connects to database multiple times. Gets some data, does some work. It then goes to get some more data and then gets an error that the "SQL Server cannot be found or access is denied". If the process is started over again without re-starting the app then no more connections are able to be made to SQL Server. All new connections result in "SQL Server cannot be found or access is denied". If the application is restarted then it will repeat the above process.
This is the first in 5 years of my experience with the software to have this problem. The application does have code written in Delphi 7. The dephi 7 / VBA code has not issues. My .NET code that performs the actual query looks like:
protected abstract DbConnection GetConnection();
protected abstract DbDataAdapter GetDataAdapter(DbCommand cmd);
protected abstract DbCommand GetCommand(DbConnection conn, String sql);
protected abstract DbCommandBuilder GetCommandBuilder(DbDataAdapter adapter);
public virtual DataTable Query(string sql)
{
var dt = new DataTable();
using (var conn = GetConnection())
{
try
{
using (var cmd = GetCommand(conn, sql))
{
using (var adapter = GetDataAdapter(cmd))
{
adapter.Fill(dt);
}
}
}
catch (Exception ex)
{
throw new SqlStatementException(sql, ex);
}
}
return dt;
}
It is my own quite and dirty DAL. When it is used it is using an OleDbConnection.
Note: Due to legacy code the connection string is configured for OleDbConnection. After taking a moment to review my code I do have the ability to change the connection type to SqlConnection. I haven't tried that yet.
On the client's machine I have not been able to reproduce the issue outside of the main application. I tried creating a little app that would make 100 calls back to back using the format above with an OleDbConnection but it executed successfully.
The failure in the main app happens in the same spot. That should give me a clue except I cannot make sense of it since it is making duplicate query, getting the same data. But I will say that the application talks to two data sources and transfers data from one to the other. Before it does the transfer it does some validation on the sources. So it talks to another database (proprietary file based) via ODBC and comes back successfully and then fails when trying to talk to SQL Server through OleDbConnection.
My suspicion is something is happening in the connection pool. That is causing a failure which in turns causes a denial of access.
Other interesting points. All worked fine for about a year, client got a new machine a couple of months ago, all work fine and then suddenly stopped. I put the application on another machine at the client's site and all worked well for a week and then the same issue appeared. We turned everything off on the client's machine but the issue persisted. I thought firewall but no luck there.
Any assistance is greatly appreciated.
Was gonna put this in a comment, but it got too big :-)
I see your connection-creating methods are abstract. This of course means that derivatives can do all sorts of bad things when they create the connection. I'd look there first.
One thing I found in a similar situation...if you're doing something in the code that creates the connection that makes the connection string unique, you won't be reusing those pooled connections. So...doing something like adding an "App=MyApp" + an incrementing number, date/time, or guid, it will destroy your ability to use pooled connections. When this happened to me, it took me forever to figure it out.
If your application was "slow enough" in the past, such that "old" pooled connections fall out of the pool, you might never see a problem...but then, say a customer gets hot new hardware...and blam...weird errors from nowhere! This might not be what's happening to you, but maybe it will give you some ideas about where to look. Good luck!

Authentication with old password no longer supported, use 4.1 style passwords

I have my website with hostgator and I want to access mysql database with C# windows application but when I tried to connect got this message:
"Authentication with old password no longer supported, use 4.1 style
password"
I have tried given solution:
SET SESSION old_passwords=0;
SET PASSWORD FOR user#host=PASSWORD('your pw here');
first query executed successfully but I got the error "Access denied for user#host" when second query executed. I can't understand why there is this problem. I am using MySQL-connecter-net 6.6.5.
I successfully connect my database with MySql workbench 5.2.47.
Can anyone help me what I can do more?
I have contact my hosting site and they make changes to my.cnf file to use 4.1 style password. and i am able to connect with mysql
mysql -u <username> -p <password> -h <hostname>;
but when i tried to connect with C# with mySQL connecter net 6.6.5 i again got this error.
I am using Visual Studio 2012 with MySQL connector 6.6.5 on Windows 8 64 bit. this is the code i used to connect
using MySQL.Data.MySQLClient;
private void button1_Click(object sender, EventArgs e)
{
string connStr = String.Format("server={0};port={1};uid={2};password={3};database={4}",
txtserver.Text, txtPort.Text, txtUser.Text, txtPassword.Text, txtDatabase.Text);
conn = new MySqlConnection(connStr);
try
{
conn.Open();
MessageBox.Show("Test Connection Succeded");
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
I can't understand where the problem is. Please Help me
I had the same problem. In my case just ran the command below connected on my database by the Workbench:
SET SESSION old_passwords=0;
SET PASSWORD FOR my_user=PASSWORD('my_password');
After that I could connnect using MySql Connector 6.6.5 in the c# code with the common mysql connection string:
"server=my_server_ip;user=my_user;database=my_db;port=3306;password=my_password;"
Today I had a similar problem in my C# application. I tried connecting to a server at hostgator.com (mysql) and connecting to localhost. After reading many posts and making many alterations, following every step but I couldn't connect to my hostgator mysql.
The solution in my case was to change the MySql Connector/NET library from version 6.* to version 5.*. After the change my application connected successfully.
While this might not be a viable solution for everyone, it may work for some.
I met this problem today, but I'v fixed it as below:
SET old_passwords=FALSE;
SET PASSWORD = PASSWORD('new pwd here');
Well, maybe the server's connection version is lower than the client, so you have to run this:"SET old_passwords=FALSE;"
Good Luck!
Had the same problem using MySqlClient package for C#. Let's break it down:
We need the database to not use old style passwords, thus we perform
SET old_passwords=0;
NOTICE there is no "SESSION" keyword. This is what allowed only your first query to work, "SESSION" implies temporary and any session settings are lost after a session ends.
Next we need to set the password of the user#host to the new password style
SET PASSWORD FOR user#host = PASSWORD('password');
This two should allow your MySqlClient
Just wanted to add to #diangelisj answer and say the root of the problem is the version of PhpMyAdmin installed on your server. In order to use the latest MySQL Data Connector class, you have to have the latest PhpMyAdmin (or issues arise). In my case, I have PhpMyAdmin 4.0.10.7 and tried using MySQL Data Connector 6.7.9, which gave the error.
What I did:
Download version 5.2.7 from https://dev.mysql.com/downloads/connector/net/6.9.html
Add .dll as reference to application
Presto!
Forget about applying SET old_password=0 since if the server is configured to use new password there is no reason to change the flag on the server if your app does not access anymore. Investigate the connector NET that you are using.
Connector 6.5.4 is the right one to use old_password, rencent version are using the new one.
The best practice would be to avoid to install the connector on the machine, just leave the NET to handle the dll if you already have it or anyway try to find MySQL.Data.DLL version 6.5.4.0 (384 kbytes)
I just solved my problem just like this:
1) Connect to the db with mysql workbench (select the "use old auth" and "send pass in cleartext"
2) Using the workbench, I ran the following several times (because it kept saying '0 rows affected'): (also change userID and password to your proper stuff)
SET SESSION old_passwords=0;
SET PASSWORD FOR userID=PASSWORD('password');
SET SESSION old_passwords=false;
SET PASSWORD FOR userID=PASSWORD('password');
3) Now go back to your app and it should run...
That is how I did it at least. I am using IX mysql and they do use old auth on their server so you must do something on your end...
I have not managed to solve the problem as the others who have responded, although I tried out everything that has been proposed.
In the end it turned out that the server on which stood my DB is not updated phpMyAdmin since version 3.5.5, and is currently being used everywhere version 4.1.14 and it is a problem.
The solution is to update your host phpMyAdmin or your own mySQL back to an earlier version in order to continue working on remote DB.
You may need this knowledge in order to solve some doubts that have arisen. :)
Today I found the same problem. I downloaded Workbench. There are some settings for workbench to connect database, as follows:
1.select tab SSL , select option 'no' in "Use SSL".
2. select tab advanced, select in Use the ole authentication Protocol.
after that Workbench working.
and follow tai1001' post.
That are all I found all steps that work.

Getting 12154: TNS:could not resolve the connect identifier specified error with .NET

I've written this simple connection in my code:
OracleConnection con = new OracleConnection("Data Source=ORCL;User
ID=agapus;Password=agap");
con.Open();
Then I run my application pressing F5 and I get the above error. This error occurs no matter if it's just a simple console app or an ASP.NET web site. I've tried both Oracle.DataAccess and the old windows oracle API. I've tried several Oracle services, all with no luck.
The environment where I'm testing this connection is a Windows Server 2008R2. I can easily connect to any database using SQLPlus or TOAD. I've tried explicitly specifying the location of the TNS_NAMES.ORA file, doesn't work either.
The only thing that works is when I specify the full path in the connection string. So if I change the above code into the below one, it'll work:
string conString = "user id=agapus;password=agap;data source=(DESCRIPTION=(ADDRESS=
(PROTOCOL=tcp)(HOST=172.16.0.121)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)))";
ID=agapus;Password=agap");
OracleConnection con = new OracleConnection(conString);
con.Open();
If you look in your sqlnet.ora file, I believe that you will find that the default domain is set to .world .
That would make the correct name of your connection ORCL.world .
You may also have .world on the end of your connection name in TNSNAMES.ora, and nothing for the default domain.
What do you get when you run tnsping?

Categories