AppHarbor: Connecting to a MySQL DB via ASP.NET MVC 5 + Dapper - mysql

I'm trying to get an application up and running on AppHarbor. It's been smooth sailing for the most part, but today I'm having trouble connecting to my MySQL database.
Using the credentials AppHarbor provided me with, I successfully connected to the mySQL database instance using dbForge Studio Express, created the necessary SQL schema, and populated the tables with data. Now I'm trying to use the following C# code to do a simple query using Dapper:
var sqlConnStringBuilder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["AppHarborMySql"].ConnectionString);
using (var db = new SqlConnection(sqlConnStringBuilder.ConnectionString))
{
db.Open();
// Do database query stuff
return result;
}
But this is the error that I'm running into, when I try to open the database connection:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error
occurred while establishing a connection to SQL Server. The server was
not found or was not accessible. Verify that the instance name is
correct and that SQL Server is configured to allow remote connections.
(provider: Named Pipes Provider, error: 40 - Could not open a
connection to SQL Server)
This is how I've declared the connection string in Web.config:
<connectionStrings>
<add name="AppHarborMySql" connectionString="server=MYDOMAIN.mysql.sequelizer.com;database=MYDBNAME;uid=MYUSERNAME;pwd=MYPASSWORD" providerName="System.Data.SqlClient" />
</connectionStrings>
Am I missing something obvious? I'm using ASP.NET MVC 5.x and the latest version of Dapper... thanks in advance!

And of course, despite having spent the better part of an hour investigating, I discover the answer immediately after posting the question.
For anyone else who may run across the same problem: I added the MySql.Web NuGet package to my MVC project, added using MySql.Data.MySqlClient; to the top of my page, and then changed my code to point from SqlConnection to MySqlConnection. Here's what my working code block now looks like:
using (var db = new MySqlConnection(ConfigurationManager.ConnectionStrings["AppHarborMySql"].ConnectionString))
{
db.Open();
// Do database query stuff
return result;
}

Related

MySQL connection string refused connection

I have installed MySQL Community server on local machine and am trying to access it from .NET Core API. Something must be wrong with either the connection string or the server configurations. I have checked the server configs to make sure TCP/IP connections are allowed, checked the connection string according to tutorials but still fail to connect, getting this exception in code:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
Tried connecting to MSSQL database and there are no issues, so nothing else could be wrong from code-side apart from the connection string itself.
The connection string:
"SqlConnectionString": "Server=127.0.0.1;Uid=admin;Pwd=admin;Database=sys;"
SQL query in code (using Dapper):
private const string SQL_INSERT_ENTITY = #"
INSERT INTO [sys].[adminportal_restapi] (Id, FeatureName, IsEnabled, LastInsertUpdate)
VALUES (#Id, #FeatureName, #IsEnabled, #LastInsertUpdate)
";
Database layout:
Found the solution - you have to use a different connector.
Basically these changes are needed:
in project.json add this dependency: "MySql.Data.Core": "7.0.4-IR-191"
and in code change new SqlConnection to new MySqlConnection
EDIT: that package got unlisted by MySQL devs without releasing a newer version (which is a complete douchebag move, IMO), so just use this one instead: "MySqlConnector": "0.11.5" syntax for connections is identical, just it doesn't support integrated security, which might suck in some cases. Good luck

Ef code first migrations on server:Cannot open database "blahblah" request by the login. The login failed

There are a million threads like this but none where the answers worked.I'm trying to get this database set up on my server (which I can remote into), but every time I try and run the web app I get this error. Why is code first not creating the database? Here's some relevant code.
Connection string in web.config
<add name="Context" connectionString="Data Source=Server\Instance;Initial Catalog=myDb;Trusted_Connection=false;User Id=User;Password=password;" providerName="System.Data.SqlClient" />
Global.asax relevant portion
Context context = new Context();
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
context.Database.Initialize(true);
if (!WebMatrix.WebData.WebSecurity.Initialized)
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("BaseContext",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
you're using integrated Windows authentication, you need to create a SQL Server login for "yourUser\ASPNET" on your SQL Server - or change your connection string to something like :
<add name="Context" connectionString="Data Source=Server\Instance;Database=myDb;Id=User;pwd=password;" providerName="System.Data.SqlClient" />
The login failed error is inside sql server error. Try if you have SQL Managment Studio logged using your data in connection string - Context.
I only thinking, but when you migrating your database recreate your user sql account and rester sql server.
Or
Try create new user by SQL Managment studio and then try usgin this data to connection string.
Check when you create user account, is not checked user must changed password first time.
I think my idea resolved your problem :)

ASP.NET / MVC4 Connection String to SQL Server 2008 error

I am working through an ASP.NET MVC4 tutorial from ASP.net. This is the second tutorial in which I am getting database connection errors. Here is the error:
An error occurred while getting provider information from the database. This can be caused by Entity >Framework using an incorrect connection string. Check the inner exceptions for details and ensure that >the connection string is correct.
Here are my connection strings. The first one was generated by the template, the 2nd was copied verbatim from the tutorial. I am running SQL Server 2008, not express. That may be my problem. The database is created automatically from the application as well. I do not have a login / password that I am aware of for this local db.
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-MvcMovie-20130830102032;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
<add name="MovieDBContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
I've looked on connectionstrings.com & asp.net to find a resolution and I am not clear on the fix. The error has to be in the connection string, but I am unsure which one, if not both, it is.
Thanks
I just changed the data source to Data Source=. and here is the error now:
There is already an object named 'PK_dbo.Movies' in the database.
Could not create constraint. See previous errors.
I tried to delete the database in sql server and was unable to when right clicking on it and pressing delete. Any ideas?

Connecting to a MySQL DB from a WPF app

I have been trying to connect a C# WPF app with a MySQL database. The database is on a Linux machine in my network. I have a lot of experience connecting with PHP but have never done it with a .NET product. I have read through everything I have found online. I have already downloaded and installed the MySQL connect stuff and attached it to the project. I have gone into the db and made sure it would accept queries from my work PC using phpMyAdmin. I have tried a wide variety of code to call the DB. I have changed the order of everything in connStr. I have changed the labels and formatting to try everything I have come across. I am able to connect to the DB with all of the web based tools that tie to this app so I know that I have the right info. I have never posted on here so I am sorry about the formatting. Everything I have read make this sound quite straightforward. I and am currently using this:
string connStr = "user=admin;database=test;server=192.168.0.37;password=******;"; MySqlConnection conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Trying to connect to: ..." + connStr); Console.WriteLine("Connecting to MySQL...");
conn.Open();
// Perform database operations
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Console.WriteLine("Done.");
and I am getting this error:
Test.vshost.exe 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
MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
at MySql.Data.MySqlClient.NativeDriver.Open()...
Thank you for your help on this!
When you are trying to contact a server in a home network using a basic modem/router, it can fail to recognize or pass along the port number you sent. In this case it was not recognizing or sending 3306 (default for mysql). This would make it so it would never work without SSH tunneling. After adding SSH tunneling it worked as advertised.

use of universal providers and mysql

I created an asp.net mvc 4 application, and added universal providers, because I need to create a custom membership provider that read users data from a my sql database.
When I work on the developer workstation it's all ok, but when I deploy on the server, where there is not Sql Server installed i receive an error. trying to open DefaultConnection.
In the InitializeSimpleMembershipAttribute that is created from the wizard, I have this:
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: false);
this call initialize the db connection, do nothing, and is not used by the custom membership provider, but must be done at startup.
the connection string is:
add name="DefaultConnection" connectionString="Data Source=...;Initial Catalog=...;User id=...;Password=..." providerName="System.Data.SqlClient" />
the problem is that I don't know how to configure to use a mysql db and pass this control in the startup of the application.
If I have to install it in a server with Sql server installed, I configure it properly, and after the initial call the mysql membership provider works without problem, but i have problems when i cannot use this workaround, and exception is raised at the call to InitializeDatabaseConnection.
How can I fix this problem?