System.InvalidOperationException: Internal Connection Fatal Error. when opening sql connection - c#

I've just started playing around with SQL on C#, and I'm trying to connect to a remote SQL server. I've added my IP to the list of hosts that have remote access permission.
My code keeps producing this error:
System.InvalidOperationException: Internal Connection Fatal Error.
at System.Data.SqlClient.TdsParserStateObject.TryPocessHeader<>
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer<>
at System.Data.SqlClient.TdsParserStateObject.TryReadByteArray<.Byte[] buff, Int32 offset, Int32 len, Int32& totalRead>
The trace is actually longer than that, but those are the first few lines.
This is the code that's causing the error (My actual connection string has the correct username, password, and database name):
connectionString = "Data Source=173.254.28.27,3306;Network Library=DBMSSOCN;Initial Catalog=myDatabase;User Id=myUserName;Password=myPassword;";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
try { myConnection.Open(); }
catch (Exception e) { Console.WriteLine(e.ToString()); }
}
Any help would be greatly appreciated.
Thanks!

EDITED
If you are using MySQL Server then your connection string is wrong!
try this connectionString :
_connectionStr = new MySqlConnectionStringBuilder
{
Server = "173.254.28.27",
Database = myDatabase,
UserID = myUserName,
Password = myPassword,
ConnectionTimeout=60,
Port = 3306,
AllowZeroDateTime = true
};
_con = new MySqlConnection(_connectionStr.ConnectionString);
try
{
_con.Open();
}
catch
{
Console.WriteLine("Error, help i can't get connected!");
}
If you are using SQLServer try disabling Connection Pool through connection string!
by adding :
Pooling=false
Good luck!

Create a udl file, if it connects then the problem is the code / application, if it does not connect, then it's your firewall, connections string, dll library etc. Well the important thing here is probably the connection string. Do the following: create an empty text file and rename it "myconnection.udl". Now double click on the file and it will launch an applet. You can configuer the connection to your database and test it. (it will pick up registered connection libraries etc). If it give OK, then open the udl file in notepad, you will see the correct connection string. Paste to your app connection settings. UDL files are generally misunderstood. They are simply a text file that holds the connection settings. They then call the connection dll. If the udl file works then you have a correct connection string 100%

Related

SQL Server Connection String in Trusted Connection format doesn't work

first time using sql with C# and I seem to be running into an unbreakable wall. I'm trying to connect to my database which is on a different server on the same domain. This is all within a winform app. Also the windows account I am using for running this winform application has read and write permissions to the sql database already (Same domain account). I've set my connection string in my app.config as follows following the advice from connectionstrings.com
<connectionStrings>
<add name="my_db" connectionString="Server=10.xx.xx.xx;Database=my_db;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
I have the following method in Helper.cs where I am setting the Connection string from the config file.
public static string CnnVal(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
Lastly, I have the following method in its own class, DbConnect.cs, and this method is called when I click a button on a form.
public void TestConnection()
{
try
{
using (var connection = new SqlConnection(Helper.CnnVal("my_db")))
{
var query = "Select 1";
System.Diagnostics.Debug.WriteLine($"Executing {query}");
var command = new SqlCommand(query, connection);
System.Diagnostics.Debug.WriteLine($"successful connection");
command.ExecuteScalar();
System.Diagnostics.Debug.WriteLine($"Successful query");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"failure {ex.Message}");
}
}
I set breakpoints on "var command" and "command.ExecuteScalar();" lines and when looking at my Watch tab in visual studio, I can see that my connection is not opened and this leads to an InvalidOperationException from SqlCommand. I'm not sure why this is happening. I used sql server migration assistant this morning to migrate the server from mysql over to sql and my info all worked then (windows auth, ip, database name). What could the outlier be here? Do I have to put the port number in my connection string somewhere? I'm using the default 1433 port. Any help would be appreciated. Thanks

The ConnectionString property has not been initialized bug

ok so i seem to be getting an annoying bug that i hope you can help me with.
I am using winforms and on an application set up form, I provide functionality to change the connection string. When the different parts of the connection string is changed and the user leaves the textbox, it writes the information to the app.config. This all works like a charm.
I have a button to test the connection, so when this is pressed after the connection string has been changed anytime while the form is still open, I hit an error:
The ConnectionString property has not been initialized
to make this a bit more complex, when i close and reopen the application, the same form is now able to make the connection and all works smoothly. Its almost as if the Config is locking itself from being queried after a change is made.
Is there something i need to do in between making changes to the app.config and attempting to open up a connection using the stored connection string.
here is my code to change the app.config:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["myconnstr"].ConnectionString = textboxCS.Text;
config.Save(ConfigurationSaveMode.Modified);
here is my code to test the connection:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["myconnstr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(constr))
{
try
{
connection.Open();
connection.Close();
MessageBox.Show("Successful Connection");
}
catch (Exception ee)
{
ee.ToString();
MessageBox.Show("Failed Connection");
}
finally
{
connection.Close();
}
this :
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["myconnstr"].ConnectionString;
needed to be replaced with:
string constr = config.ConnectionStrings.ConnectionStrings["myconnstr"].ConnectionString;
The problem was that it was trying to open ConfigurationManager twice
Thanks for all the help guys

Unable to connect to any specified mysql C#

I can't connect to my sql server, i tried some fixes from stackoverflow and google and it didn't help me. Thanks.
connString = "SERVER ='''myserverip''';PORT=3306;DATABASE=mydatabase;UID=myuser;PASSWORD=mypassword";
try
{
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
MessageBox.Show("Connection success");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
To configure myuser I used this on my linux vps.
CREATE USER 'myuser'#'localhost' IDENTIFIED BY 'mypassword'; CREATE USER 'myuser'#'%' IDENTIFIED BY 'mypassword'; GRANT ALL ON *.* TO 'myuser'#'localhost'; GRANT ALL ON *.* TO 'myuser'#'%';
i tried : Unable to connect to any of the specified mysql hosts. C# MySQL ( i tried to use MySqlConnectionStringBuilder, don't specify the port, instead of password in connection string i typed psw);
Disable my pc firewall, disable linux server firewall
MySqlConnectionStringBuilder does enable you to specify port. Just tested, this works just fine:
MySqlConnectionStringBuilder csb = new MySqlConnectionStringBuilder();
csb.Server = "192.168.1.105";
csb.Port = 3307;
csb.Database = "test";
csb.UserID = "me";
csb.Password = "mypassword";
cn = new MySqlConnection(csb.ToString());
cn.Open();
Are you quite sure your MySql server actually accepts incoming connections over TCP? By default that is disabled.
So, after searching on google how to setup sql connection in linux, and trying different setups hardly I fixed it so I want to share with stackoverflow how I fixed it. Thanks for help #Avo Nappo.
First you need to comment out the line #bind-address from your sql config.
The accepted answer here :MySQL root access from all hosts .
Then I create a user using this command CREATE USER 'golden'#'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'golden'#'%';
And in c# I used my default connection string that is in the question. I don't know why but MySqlConnectionStringBuilder dose not work on my pc. I hope this will help someone. Have a nice day and keep coding.
You must go in your Remote MySQL in your C-Pannel and Add Access Host first and change this code
connString = "SERVER ='''myserverip''';PORT=3306;DATABASE=mydatabase;UID=myuser;PASSWORD=mypassword";
to
connString = "SERVER =*Put here your Hostname with Port*;DATABASE=mydatabase;UID=myuser;PASSWORD=mypassword;";
Or use this Method
MySqlConnectionStringBuilder ConStD = new MySqlConnectionStringBuilder();
ConStD.Server = "Hostname that get from Manage Access Hosts";
ConStD.Port = Port that get from Manage Access Hosts;
ConStD.Database = "YourDatabaseName";
ConStD.UserID = "yourUsername";
ConStD.Password = "yourpassword";
try
{
MySqlConnection conn = new MySqlConnection(ConStD.ToString());
conn.Open();
MessageBox.Show("connection Success");
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
It's Must working For You
1-Un check all Firewall and Network protection settings
2-Go in database management system running icon like wamp green icon
3-Go to Mysql CMD
3a-
CREATE USER 'muzamil'#'%' identified by 'muzamil';
grant all privileges on *.* to 'muzamil'#'%';
flush privileges;
These three commands run one by one
4-Windows Defender Firewall
then Click on Advance settings
==> Inbound Rules
->Enable riles Remote Desktop TCP All Rules
5:
C:\wamp64\alias
open this File then
change local to
==> Require all granted
==> Allow from all
Your remote server
will work with c# application

C# SQL Server Connection Issue

I am having problems connecting to a SQL Server database from C#.
The exception that returns is the login has failed for the specified user, which is clear enough. However, I am not sure why it fails as the username and password are definitely correct. Are there any settings I need to enable on the SQL Server to allow this to happen, as it is a default express install,
Thanks,
Below is my connection code if I'm missing anything obvious.
static void Main(string[] args) {
try
{
SqlConnection con = new SqlConnection(#"Data Source = .\SQLEXPRESS;Initial Catalog=furniture_display;User ID=login;Password=login");
con.Open();
Console.WriteLine("all ok");
con.Close();
}
catch (SqlException err)
{
Console.WriteLine(err);
}
}
According to your code Data Source = .\SQLEXPRESS, you'r trying to connect to a local server. If so you don't need any ID and Password. And be aware of using Catalog, it's somehow tricky and I hate it. To know how it's working, check this out.
Actually I'm using this code and it works like a charm:
SqlConnection con = new SqlConnection(#"Server = localhost; Database = furniture_display; Integrated Security=True;");

Connection to Microsoft SQL server error

Below is a concise version of my code as it pertains to db access.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace DataAccess
{
public class DbConnection
{
public string connString = "Data Source=[Insert IP];Initial Catalog=MOSAIQ;Persist Security Info=True;User ID=[Insert User];Password=[Insert Password]";
public void CreateConnection()
{
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
For security reason I've removed IP and user credentials. That being said I copied the above connection string directly from the properties of the server explorer which successfully connected to my db.
While stepping through this code the following error is caught upon executing conn.Open()
Seems pretty obvious that there is an issue during validation. The credentials supplied are those used for SQL authentication.
Why is it that I can connect via server explorer but not directly via my code? What does Visual Studio's do for me that I can't seemingly do myself?
Ports are open, firewall is not an issue. I'm stumped and as a rookie in this matter would appreciate further guidance.
I'm trying to connect to SQL Server 2008 R2, using Visual Studio's 2013.
As a test try to use the SqlConnectionStringBuilder
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
//Or Supply User and Password
builder["Connect Timeout"] = 1000;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
If you do that and are still experiencing the error then move on to testing the networking.
<add name="RM_V1.0CS1" connectionString="Data Source=SERVER;Initial Catalog=DB;User ID=sa;Password=Password" providerName="System.Data.SqlClient" />
Edit Explicitly Set Provider:
For those that might experience similar issues. I save my solutions on a network drive through work. Because I was opening and running my solution from this network location for a reason I'm yet unaware of it was using my windows credentials instead of the SQL credentials that I was passing to the SQL server. Once the solution was moved to my local workstation the method ran as expected. Any insight as to what more specifically was occurring would be of interest.

Categories

Resources