The ConnectionString property has not been initialized bug - c#

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

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

c# sqlite database locked when inserting

I am using SQLite in a C#
I have an insert query in a win form that works but on another win form that doesn't. when I have read about the issue it says it might be because there is an open connection somewhere but I have checked it all and even used SQLiteConnection.ClearAllPools(); after every close. now the 1st winform have only 1 open / close, the other one has 3.
I have tried the query using SQLite Browser to make sure it wasn't an issue with the query and it worked successfully. now when I debugged the issue occurs when this line executes cmd.ExecuteNonQuery(); that, of course, executes the query (insert into ....). so I tried changing the type of the table primary key (from varchar to integer). and I still have the issue. below is a sum of how it is.
myconnection = new SQLiteConnection(connectionString);
myconnection.Open();
//select stuff here
//verifications here
//insert inside verification
//finally { myconnection.close(); }
Did you try wrapping your connection in a using statement?
using(var myconnection = new SQLiteConnection(connectionString))
{
myconnection.Open();
//Your code here
}
This will call Dispose method of the connection regardless of execution path, which could possibly be doing more than just closing the connection.
Be aware to click on Write changes on SQLite browser,
if it is running and there are any unsaved changes!
In my case it was very stupid of me, I was making changes in the SQLite browser and did not click on write changes, which locked the DB to be modified by the services. After I clicked the Write changes button, all the post requests worked as expected.
According to #Rohan Shenoy in this topic: SQLite Database Locked exception
may be you should also try this
using (var con = new SQLiteConnection { ConnectionString = "connectionstring" })
{
using(var cmd = new SQLiteCommand { Connection = con })
{
// check state connection if open then close, else close proceed
if(con.State == ConnectionState.Open)
con.Close();
//then
try
{
// try connection to Open
con.Open();
}
catch
{
//catch if found error, message : 'Invalid Connection string'
}
........ // insert query here
} // Close Command
} // Close Connection

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;");

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

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%

Can't commit changes to SQL Server Compact Edition database

I have a problem,
private void button_Submit_Click(object sender, EventArgs e)
{
try
{
string connectionString = #"Data Source=Database_TouchPOS.sdf;Persist Security Info=False;";
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
using (SqlCeCommand command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "INSERT INTO Product (Title,Price,Category_Id) VALUES (#title, #price,#category_Id)";
command.Parameters.AddWithValue("#title", textBox_Title.Text);
command.Parameters.AddWithValue("#price", textBox_Price.Text);
command.Parameters.AddWithValue("#category_Id", comboBox_Category.SelectedIndex);
command.ExecuteNonQuery();
MessageBox.Show("Product Added Successfully...");
}
connection.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Everything seem to be fine, but still can't add data into database.
I did try with complete database path, example c:\project\database.sdf
I did a lot of search before asking. I saw similar problems but not even a single one works for me.
Data are added when compiling but not committed to database. I can see the data after second attempt of debugging.
Please kindly try to explain in detail.
Thanks
You are probably facing this, http://erikej.blogspot.com/2010/05/faq-why-does-my-changes-not-get-saved.html suggest you use a full path to your database file in your connection string.
Did you try to use transactions explicitly?
IDbTransaction transaction = connection.BeginTransaction();
//add to database
transaction.Commit(); // before close connection
This is a very old thread, so I don't know if it will help anyone if I put my answer.
I had this problem, too.
When I executed an update or insert code in C#, apparently, everything was ok, but when I looked up the database, there was no change.
The thing was that while debugging I had the database opened in a Management Studio. And somehow this obstructed the database changes even when there was no error message.
Closing the Management Studio and opening it after executing the code, the changes where perfectly stored in the data base.
Regards.
complete example for those seeking like me... #"Data Source=C:\Users\MYPC\Documents\Visual Studio 2010\Projects\MyProjectFolder\MyProject-1\bin\Debug\MyDatabase.sdf;Persist Security Info=False;";
thank for this example. This saved my day.

Categories

Resources