Getting error "A network-related or instance-specific error occurred while establishing a connection to SQL Server" when using MySQL and Authorization - mysql

I have an ASP.NET project running on .NET Framework 4.8 and using MySQL for the database. Everything was working fine, till I decided to user Authorization. I have the following:
[Authorize(Roles = "Admin")]
public class ApproveActionsController : DaysOffBaseController
{
}
The moment I try to access the URL: https://myApp/DayOffModule/ApproveActions/ApproveDaysOffList
I'm getting the following error message and the app is throwing SqlException
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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I have read a lot and it looks like it's thinking that it thinks I'm using SQL Server or trying to connect to it. I have tried looking everywhere in the app for System.Data.SqlClient and changed it to MySql.Data.MySqlClient but it's still throwing the same Exception.
When I remove the [Authorize(Roles = "Admin")] from the controller above - I'm not having this issue.
Here is the entire stack:
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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
SQLExpress database file auto-creation error:
The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:
If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: http://go.microsoft.com/fwlink/?LinkId=160102. If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist.
If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database.
Sql Server Express must be installed on the machine.
The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +1524
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +706
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +57
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +1186
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +315
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +128
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +265
System.Data.SqlClient.SqlConnection.Open() +133
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +82
[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +175
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +121
System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +57
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +475

Related

EFCore MAC - Unable to find an entry point named 'AppleCryptoNative_SslCreateContext'

when running
dotnet ef database update --startup-project ../webapi/webapi.WebAPI.csproj
on my MAC 10.13.5
I get this error -
System.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught) ---> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception. ---> System.EntryPointNotFoundException: Unable to find an entry point named 'AppleCryptoNative_SslCreateContext' in shared library 'System.Security.Cryptography.Native.Apple'.
at Interop.AppleCrypto.SslCreateContext(Int32 isServer)
at System.Net.SafeDeleteSslContext.CreateSslContext(SafeFreeSslCredentials credential, Boolean isServer)
at System.Net.SafeDeleteSslContext..ctor(SafeFreeSslCredentials credential, SslAuthenticationOptions sslAuthenticationOptions)
at System.Net.Security.SslStreamPal.HandshakeInternal(SafeFreeCredentials credential, SafeDeleteContext& context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, SslAuthenticationOptions sslAuthenticationOptions)
--- End of inner exception stack trace ---
...
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)
I originally thought this was my local docker database was not available but when connecting to new database instance it still occurs, this was working yesterday.
Whilst typing this I came across this, but thought would just add the answer as someone on a MAC EF Core install may miss that also when searching -
A connection was successfully established with the server, but then an error occurred during the pre-login handshake
Cleaning my project (I personally deleted all the folders) and rebuilding, sorted it!

SQLException error when connecting with java

I have been facing a simple sql connection error, and i m tired of fixing it. I installed sql server 2014 and then sql server 2017, add rules to firewall and even turned off the firewall. services restarted multiple times.
Went to configuration manager, enabled everything, added all the jar required, done clean and build, done all searches on this issue in google, still that same issue comes in again and again. System used are
- Windows 10.
- Sql server management studio 2017.
- Netbean 8.1
code :-
import java.sql.*;
public class DbConnect {
public static void main(String[] args) throws SQLException,ClassNotFoundException {
String url = "jdbc:sqlserver://localhost:1433;databaseName=productlist;user=db2017;password=db2017";
//commented :-String url = "jdbc:sqlserver://DESKTOP-7CI6DU0\\NIT2017:1433;databaseName=productlist;user=db2017;password=db2017";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
System.out.println("test");
Statement sta = conn.createStatement();
String Sql = "select * from productlist";
ResultSet rs = sta.executeQuery(Sql);
while (rs.next()) {
System.out.println(rs.getString("CatName"));
} } }
Below is exception error comes again again, after so much troubleshooting.
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1033)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:817)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:233)
at DbConnect.main(DbConnect.java:11)
C:\Users\Nitish\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
Before giving up, thought to check here...
Your commented-out connection string suggests you are connecting to a named instance. A default SQL Server instance (not-named) listens on port 1433 unless configured otherwise. A named instance uses a dynamic port, which is not 1433, unless configured otherwise. One can have only one default instance per machine and every SQL instance must listen on a different port.
You can identify the port a SQL instance is listening on using SQL Server Configuration Manager or by viewing the SQL Server error log. The error log will include messages for each interface and port SQL Server is listening on. The message will be like "Server is listening on [ 'any' 1433]." The port can be changed using SSCM and will be effective after restarting the SQL Service.
To test port connectivity, you can use TELNET:
TELNET YourServer 1433
You'll see and empty window if the connection is successful, otherwise and error.
If you don't have TELNET installed, you can test the port connectivity with this Powershell command from a command-prompt window:
powershell -Command echo ((new-object Net.Sockets.TcpClient).Client.Connect('YourServer', 1433)) 'success'
You'll see the success message upon successful connection, otherwise a socket exception.
Note that the dynamic port is assigned during installation and the instance will attempt to use the same port upon each startup. However, be aware the port number could change if that port is unavailable at startup. One can configure a static port (including port 1433) using SSCM to avoid the port number changes of a named instance.

Deploy .NET app to Azure using another server database

Is possible to deploy my .NET application to azure using as connection string another server MySQL database?
I created an application in .NET MVC. It connects to my private server MySQL Database. The application works fine. However, when I deployed it to Azure server, it doesn't working.
When I try to publish, I don't have MySQL as datasource:
When I run it in Azure server, I get the error:
[MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.]
MySql.Data.MySqlClient.NativeDriver.Open() +1228
MySql.Data.MySqlClient.Driver.Open() +22
MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings) +218
MySql.Data.MySqlClient.MySqlPool.GetPooledConnection() +287
MySql.Data.MySqlClient.MySqlPool.TryToGetDriver() +93
MySql.Data.MySqlClient.MySqlPool.GetConnection() +65
MySql.Data.MySqlClient.MySqlConnection.Open() +566
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +41
My connectionstring:
<connectionStrings>
<add name="myEntities" connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.ssdl|res://*/Models.MyModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=myServer;user id=userName;password=Password;database=myDB"" providerName="System.Data.EntityClient" />
</connectionStrings>
Does anyone know how to fix it?
Thanks
You can certainly connect to a MySQL server from an MVC web app. Your MySQL server can be hosted in Azure, AWS, or any other hosting provider that lets you connect to your database remotely. However, making database calls outside of your Azure data enter will cause a delay due to network latency.

Entity Framework 4.1 The provider did not return a ProviderManifestToken string Exception

I downloaded the Asp.NET MVC 3 EntityFramework Code first sample application in vb.net and modified the connection string as I don't have SQL Server Express Edition to try it with Sql Server 2008 Web Edition
<add name="ApplicationServices"
connectionString="Server=MyPC\Sql2008;Trusted_Connection=True;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
when I try to run the application then ProviderIncompatibleException exception is thrown. And following error is displayed in the browser window.
Server Error in '/' Application.
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: Shared Memory Provider, error: 40 - Could not open a connection to SQL Server)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: 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: Shared Memory Provider, error: 40 - Could not open a connection to SQL Server)
Source Error:
Line 24:
Line 25:
Line 26: #For Each item In Model
Line 27: #
Line 28:
Source File: C:\Documents and Settings\Shishir Shukla\My Documents\Downloads\CodeFirstEFVB\CodeFirstMVC\Views\Blog\Index.vbhtml Line: 26
The connection string which I have used works perfectly with my asp.net webforms application and also Winforms application.
Please help me soon to get rid of this problem as I have just switched to MVC.
The problem was with the connection string , I changed it to this and it worked ..
<add name="DBCon" connectionString="Data Source=.\SQL2008;Initial Catalog=TestDB;Integrated Security=True" providerName="System.Data.SqlClient" />
Can you provide a link to the project you downloaded?
You are using Windows Authentication, does the IIS account have permissions to the db?
Finally, verify your dbContext class is named "ApplicationServices". Otherwise, you may need to use the constructor that takes in a nameOrConnectionString.
Your connection string is a valid SQL connection string, but you need an Entity Framework connection string.
When you create your EF Model, create a new connection string from scratch. That will resolve this issue.
You can look at the new conneciton in your web.config, and you wil see that an Entity connection contains additional metadata as part of the connection string, and wraps the SQL conneciton string.
UPDATE:
A valid Entity connection string will look something like this:
<add name="MyDatabaseEntities" connectionString="metadata=res://*/Models.MyDatabase.csdl|res://*/Models.MyDatabase.ssdl|res://*/Models.MyDatabase.msl;provider=System.Data.SqlClient;provider connection string="data source=SERVER;initial catalog=MyDatabase;persist security info=True;user id=userid;password=password;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
However, you should let Visual Studio build the connection string for you.

Subsonic not working with MySQL (5.0.51a)

I am trying to use Subsoinc 3.0.0.1 to connect to mysql db.
I added dll reference and connection string to app.config
Then I copied templates from ActiveRecord folder to folder in my solution and edited namespace and connection string but then i get this error:
Error 10 Running transformation: System.Data.SqlClient.SqlException: 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)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.VisualStudio.TextTemplatingB345C0F834877921095C8F23912FC356.GeneratedTextTransformation.GetReader(String sql)
at Microsoft.VisualStudio.TextTemplatingB345C0F834877921095C8F23912FC356.GeneratedTextTransformation.LoadTables()
at Microsoft.VisualStudio.TextTemplatingB345C0F834877921095C8F23912FC356.GeneratedTextTransformation.TransformText() C:\Users\Hex\Documents\Visual Studio 2008\Projects\Ceger\Ceger.DAL\Models\Structs.tt 1 1
Then i found MySQL.ttinclude and Settings.ttinclude in TemplateProviders and replaced files form ActiveRecord with them but that didnt change everything.
I also tried with LinqTemplates.
Like the README says :) you need to use the MySQL.ttinclude in the TemplateProviders folder...
Now i got it.
I have to rename MySQL.ttinclude to SQLServer.ttinclude or to manualy change all reference in all files from SQLServer.ttinclude to MySQL.ttinclude.
and Settings.ttinclude in TemplateProveders folder is not needed. (it has been removed from 3.0.0.2)