When I start my application I get: The ConnectionString property has not been initialized.
Web.config:
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=localhost\sqlexpress;Initial Catalog=mydatabase;User Id=myuser;Password=mypassword;" />
</connectionStrings>
The stack being:
System.Data.SqlClient.SqlConnection.PermissionDemand() +4876643
System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection) +20
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
I'm fairly new to .NET and I don't get this one. I found a lot of answers on Google, but none really fixed my issue.
What does that mean? Is my web.config bad? Is my function bad? Is my SQL configuration not working correctly (I'm using sqlexpress)?
My main problem here is that I'm not sure where to start to debug this... anything would help.
EDIT:
Failling code:
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.AppSettings["ConnectionString"],
CommandType.Text,
sqlQuery,
sqlParams);
sqlQuery is a query like "select * from table". sqlParams is not relevant here.
The other problem here is that my company uses MySQLHelper, and I have no visibility over it (only have a dll for a helper lib). It has been working fine in other projects, so I'm 99% that the error doesn't come from here.
I guess if there's no way of debuging it without seeing the code I'll have to wait to get in touch with the person who created this helper in order to get the code.
Referencing the connection string should be done as such:
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString,
CommandType.Text,
sqlQuery,
sqlParams);
ConfigurationManager.AppSettings["ConnectionString"] would be looking in the AppSettings for something named ConnectionString, which it would not find. This is why your error message indicated the "ConnectionString" property has not been initialized, because it is looking for an initialized property of AppSettings named ConnectionString.
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString instructs to look for the connection string named "MyDB".
Here is someone talking about using web.config connection strings
You get this error when a datasource attempts to bind to data but cannot because it cannot find the connection string. In my experience, this is not usually due to an error in the web.config (though I am not 100% sure of this).
If you are programmatically assigning a datasource (such as a SqlDataSource) or creating a query (i.e. using a SqlConnection/SqlCommand combination), make sure you assigned it a ConnectionString.
var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[nameOfString].ConnectionString);
If you are hooking up a databound element to a datasource (i.e. a GridView or ComboBox to a SqlDataSource), make sure the datasource is assigned to one of your connection strings.
Post your code (for the databound element and the web.config to be safe) and we can take a look at it.
EDIT: I think the problem is that you are trying to get the Connection String from the AppSettings area, and programmatically that is not where it exists. Try replacing that with ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString (if ConnectionString is the name of your connection string.)
The connection string is not in AppSettings.
What you're looking for is in:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...
I stumbled in the same problem while working on a web api Asp Net Core project.
I followed the suggestion to change the reference in my code to:
ConfigurationManager.ConnectionStrings["NameOfTheConnectionString"].ConnectionString
but adding the reference to System.Configuration.dll caused the error "Reference not valid or not supported".
To fix the problem I had to download the package System.Configuration.ConfigurationManager using NuGet (Tools -> Nuget Package-> Manage Nuget packages for the solution)
I found that when I create Sqlconnection = new SqlConnection(),
I forgot to pass my connectionString variable. So that is why I changed the way I initialize my connectionString (and nothing changed).
And if you like me just don't forget to pass your string connection into SqlConnection parameters.
Sqlconnection = new SqlConnection("ConnString")
This what worked for me:
var oSQLConn = new
SqlConnection(
System.Configuration.ConfigurationManager.ConnectionStrings["Conn1"].ToString()
);
If you tried every answer mentioned above then there is the possibility that you are creating a new SQL connection based on the wrong sqlconnection check condition.
Below is the scenario :
The common method to return new SQL connection if it is not previously initialized else will return the existing connection
public SqlConnection GetSqlconnection()
{
try
{
if(sqlConnection!=null)
{
sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
return sqlConnection;
}catch(Exception e )
{
WriteLog.WriteErrorLog(log, "GetSqlconnection() | ", e.Message, e.StackTrace);
throw e;
}
// return sqlConnection;
}
//here two methods which are using above GetSqlconnection() method
public void getUser()
{
//call to GetSqlconnection() method to fetch user from db
//connection.open()
//query execution logic will be here
//connection.close() <---here is object state changed --->
}
public void getProduct()
{
//call to GetSqlconnection() method with no connection string properties
//connection.open() ; <--- here exception will be thrown as onnectionstring-property-has-not-been-initialized
//query execution logic will be here .
//connection.close().
}
As soon as you close the connection in getUser() method there will two change in sqlconnection object
1.Status changed from 'Open' to 'Close'
2.ConnectionString property will be change to ""
hence when you call GetSqlconnection() method in getProduct() ,
accroding to if-Condition in GetSqlconnection() ,it will return the existing object of sqlConnection but with status as 'Closed' and ConnectionString as " ".
thus at connection.open() it will throw exception since connectionstring is blank.
To solve this problem while reusing sqlConnection we should check as below in GetSqlconnection() method :
try
{
if(sqlConnection==null || Convert.ToString(sqlConnection.State)=="Closed")
{
sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
return sqlConnection;
}catch(Exception e )
{
WriteLog.WriteErrorLog(log, "GetSqlconnection() | ", e.Message, e.StackTrace);
throw e;
}
In my case, I missed a single letter in the word "ConnectionStrings" so it didn't match with the appsettings.json properties thus it gave me this error. An error could not be as deep as you may think. Start debugging by spelling mistakes.
I couldn't fix this exact problem nor have time to investigate, but in my case, it was related to Windows Server 2012 R2 or the framework version. The exact same code, app and config file worked flawlessly on other machines running other Windows versions. Tryed with at least the consumer versions (Windows 8, 10 and 11). Just Windows Server 2012 refused with the error in
System.Data.SqlClient.SqlConnection.PermissionDemand()
IN the startup.cs provide ConnectionStrings
for eg:
services.Configure<Readconfig>(Configuration.GetSection("ConnectionStrings"));
Use [] instead of () as below example.
SqlDataAdapter adapter = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["FADB_ConnectionString"].ConnectionString);
DataTable data = new DataTable();
DataSet ds = new DataSet();
Related
I have a SqLConnection method that takes a connection string as a parameter. I am using Veracode to check for vulnerabilities in my code, and I got the following CWE 15 error:
This call to system_data_dll.System.Data.SqlClient.SqlConnection.!newinit_0_1() allows external control of system settings. The argument to the function is constructed using untrusted input, which can disrupt service or cause an application to behave in unexpected ways. The first argument to !newinit_0_1() contains tainted data from the variable connectionString. The tainted data originated from an earlier call to saturnrearchdataaccess_dll.SaturnRearchDataAccess.AdoHelper.GetDirectSqlCommand.
I am setting the connectionString in my Web.config file, and to my understanding it is complaining that it could be changed at some point.
Is there a way to check if the connectionString is tainted or not?
Here is my function:
public static SqlConnection GetSqlConnection(string connectionStringName)
{
var connectionString = ConfigurationManager.ConnectionStrings[environ + connectionStringName].ConnectionString;
var conn = new SqlConnection(connectionString);
return conn;
}
I'm learning how to use MVC template to create ASP.NET web applications.
As the title states, I'm using MySql, I can see the connection in the server explorer > Data Connections, from where I got the connectionString and it's properly connected.
Access denied for user 'root'#'localhost' (using password: NO)
is the error I'm getting when I try to save data to the (currently empty) database.
This is my connectionString
<connectionStrings>
<add name="dbname" connectionString="server=localhost;user id=root;persistsecurityinfo=True;database=dbname" />
</connectionStrings>
The error I'm getting is in the following line
public static int SavedData<T>(string sql, T data)
{
using (IDbConnection cnn = new MySqlConnection(GetConnectionString()))
{
return cnn.Execute(sql, data); //here is the error
}
}
I don't understand. It says the error is for the user and it isn't using a password? A password is being used, and it's properly set. Any ideas on how to fix this? I've read many other threads but those mainly have errors in the password or the configuration using other tools like xampp, php, etc, which isn't my case.
EDIT:
I followed this tutorial which uses SQL and not MySql, and uses a tool called Dapper which I don't know what it is used for, in the stacktrace I see the following errors
Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) +85
Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) +763
Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType) +117
I'm currently investigating about dapper with MySQL.
Edit 2:
I tried modifying the connection string, all values are correctly set. But I still get exactly the same error, I didn't think that was the actual problem (I had to modify the root password because I was using double quotes and # in the password. Anyways, this is how it looks now, and the connection is tested and works OK.
<connectionStrings>
<add name="dbname" connectionString="Persist Security Info=False;database=dbname;server=localhost;Connect Timeout=30;user id=root; pwd=_password" />
</connectionStrings>
I believe the code was pretty easy to follow, also what I wanted to do, but I understand that more experienced programmers may have considered it incomplete now. What I was trying to do was to save data, and was unable to, due to an access denied type of error, which I think comes from the way Visual Studio handles the projects that can be added as SQL server projects, which I couldn't do with a MySQL project (in the tutorial I was following, he copied the string from the server explorer project he added and then pasted it in connectionString on web.config, which clearly didn't work for me), I also learnt my lesson about the GetConnectionString() method, which wasn't explained in my question, that's why it was voted for closing the question, but I knew it was working (maybe was not doing what it was supposed to, though; I got rid of it), still, perhaps the problem was there.
so I ended up doing the following, which works OK
public static void SavedData(int _SomeField)
{
FooModel data = new FooModel
{
SomeField = _SomeField
};
MySqlConnection dbConnection;
MySqlConnectionStringBuilder connectionBuilder = new MySqlConnectionStringBuilder();
connectionBuilder.Server = "localhost";
connectionBuilder.UserID = "root";
connectionBuilder.Password = "password";
connectionBuilder.Database = "foo";
dbConnection = new MySqlConnection(connectionBuilder.ToString());
String query = String.Format("insert into foo.foo (SomeField) values ('{0}')", #data.SomeField);
dbConnection.Open();
MySqlCommand cmd = new MySqlCommand(query, dbConnection);
cmd.ExecuteNonQuery();
dbConnection.Close();
}
I have a piece of code that I reuse that helps me connect to an adt database and read the data.
using Advantage.Data.Provider;
...
protected DataTable FillTable(string tableName)
{
DataTable table = new DataTable();
using (var conn = new AdsConnection(connectionString))
using (var adapter = new AdsDataAdapter())
using (var cmd = new AdsCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select * from " + tableName;
adapter.SelectCommand = cmd;
conn.Open();
adapter.Fill(table);
conn.Close();
}
return table;
}
This code works perfectly the first time I go through it, but gives the following exception the second time I call it with a different table name.
System.EntryPointNotFoundException: 'Unable to find an entry point named 'AdsIsConnectionAlive' in DLL 'ace32.dll'.'
I would like an explanation.
I've tried to read up on this error, but all the possible scenario's I've found don't explain why it works the first time. They mention problems with the DLL like it being the wrong version or some incompatability with the .NET version, ...
If I change the order of the calls the code still fails on the second time, so I know the problem isn't with the name of the table or the way I call my code. The problem is probably with me not closing the connection correctly. I've tried adding more braces just to make sure that that part runs correctly and I've debugged to make sure that the first conn.Close(); is executed correctly.
I could place all my code within this code and only use one connection that I keep open as long as I need it. That would bypass my problem, but I would like to avoid that and to understand what I'm doing wrong.
This is most likely caused by loading an older version of ace32.dll from a newer version of the ado.net components. The AdsIsConnectionAlive was introduced in a later version of the DLL - not sure about the exact version probably 6.0 or later.
The first time the connection was made, the ado.net component knows that the connection was not alive so there was no need to call the IsAlive entry point. The second time around, since there was already a connection made to the same connection path, it would try to reuse it by checking to see if it is still alive. I think that there is a way to disable the connection caching but do not remember the detail. A better solution would be to make sure that the advantage DLLs are matching version.
I've searched quite a bit and turned up nothing helpful so here I am.
I have written an app in C# (Any CPU setting) that has been running on Windows 7 and XP x86 for some time now without error.
Recently my office has upgraded my workstation to Windows 7 x64 (from x86).
When I run my application in Visual Studio 2010 I receive no errors at run or compile time. It works as designed.
My VS2010 version is 10.0.30319.1 RTMRel from our MSDN subscription, Framework is 4.0.30319 RTMRel
When I run my compiled application directly I receive an error when with the SqlConnection object. It does not matter if i choose ANY CPU or x86 the same errors occur.
In my class file this is the routine:
public static SqlConnection getDBConnection()
{
SqlConnection sqlConn = null;
try
{
sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["KpH2Oprod"].ConnectionString);
sqlConn.Open();
}
catch
{
throw;
}
finally
{
if (sqlConn == null)
{
sqlConn.Dispose();
}
}
return sqlConn;
}
Some manual tracing I found the error to be thrown not after SqlConnection sqlConn = null; when it's first instantiated but when I actually set it on the line:
sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["KpH2Oprod"].ConnectionString);
I have changed this line to:
sqlConn = new SqlConnection();
sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings["KpH2Oprod"].ConnectionString;
to see if it was the SqlConnection or to Configuration manager and indeed it throws on the sqlConn = new SqlConnection(); line. In fact this was the way I started and changed it to the previous, no matter, both throw error on using the new directive.
The actual error message I get back is (some of which is my own message):
I believe that this might be related to how the SQL object are registered but the message is truncate in the center of the first few lines (not my doing) that point to the parameter g being null. Again this works in the debugger flawlessly.
RunTimeError :
Value cannot be null.
Parameter name: g
at System.Guid..ctor(String g)
at kpH2O.frmMain..ctor() (mscorlib)
ACTION :
UPDATEINCIDENT ()
PROGRESS :
WORKING ()
RunTimeError :
Object reference not set to an instance of an object.
at kpH2O.db.getDBConnection()
at kpH2O.db.getIncidentIDFromNumber(String incidentNumber)
at kpH2O.frmMain.updateHeatIncident() (kpH2O)
ERROR :
Process UPDATEINCIDENT: FAILED (doStartUp)
This is an out of the box VS2010 install without any addons. Any assistance is GREATLY appreciated.
how is the Connection string defined in your .config file for starters..?
would need to see that much
also I would look at defining your sqlConn like this
sqlConn = ConfigurationSettings.AppSettings["connectionString"]; //assuming this is what you named your connection string..
Second I would make use of Try catch {} as well as putting the using (){} within that try
if you do not want to dispose of that sqlConn.. then make it a static property
public static SQLConnection sqlConn = null;
then if you need to use it .. use the new construct within the using() {} as described above..
look at this link as well if you want to Enumerate connection string variables using your original construct ConfigurationSetting and manager
To validate functionality, I would test with a snippet like this. Your current code has a flaw in the disposition logic which is just complicating things.
string connectionString = ConfigurationManager.ConnectionStrings["KpH2Oprod"].ConnectionString;
using( SqlConnection sc = new SqlConnection( connectionString ) )
{
sc.Open();
// perform simple data access
}
I have the following method inside class DBConnection. I call the method like this: SQLiteConnection conn = DBConnection.OpenDB(); when I want to open an connection, so that I can execute my queries. I can call a similar method when I want to close the connection.
The method:
public static SQLiteConnection OpenDB()
{
try
{
//Gets connectionstring from app.config
string myConnectString =
ConfigurationManager.ConnectionStrings[
"LegMedSQLLite.Properties.Settings.LegMedSQLLiteDBConnectionString"].ConnectionString;
var conn = new SQLiteConnection(myConnectString);
conn.Open();
return conn;
}
catch (SQLiteException e)
{
MessageBox.Show(e.ToString(), "TEST");
return null;
}
}
This all works fine and dandy. The problem is the try-catch though. Let us imagine the following scenario:
The database file has been
moved/delete.
The exception will never be thrown. Actually, the first catch I stumble upon is when I execute my first query - where it figures that there is no such table(s) and it throws its own exception.
I was stunned by this weird phenomenon, but I soon found out that SQLite creates a new
empty database. By empty is mean no tables, nothing, just an SQLite database file with the same name as the old database which was supposed to be there.
This is an issue, I want the application to know if there is something wrong (database not found, corrupted, being used by another process etc.) as soon as I try to call SQLiteConnection conn = DBConnection.OpenDB();.
Naturally, I could try call a File.Exists in my method, but that doesn't seem like a proper solution. Any help?
If you're using System.Data.SQLite, you can add "FailIfMissing=True" to your connection string. SQLiteConnection.Open() will throw a SQLiteException if the database file does not exist.
string ConnectString = "Data Source=file.sdb; FailIfMissing=True";
DbConnection db = new SQLiteConnection(ConnectString);
db.Open(); // Fails if file.sdb does not exist
See SQLite Connection String Samples for another example, look for "Disable create database behaviour".
If you're using Microsoft.Data.Sqlite, you can specify an open mode with Mode=ReadWrite instead of Mode=ReadWriteCreate.
I haven't used SQLite but that is pretty bizarre behaviour to auto create a brand new database.
You could just adjust your try block to do a Select top 1 * From Table immediately after you open the connection, if it works, throw away the result and continue to return your conn object. If it fails, the exception handler should fire.
If you want to detect database corruption issues on start up , you can execute the command
pragma integrity_check;
or
pragma quick_check; ( which is faster, but less thorough )
This returns a single row with the value "ok".
Otherwise it will report errors that it encounters.
For sqlite use this: Suppose you have connection string in textbox txtConnSqlite
Using conn As New System.Data.SQLite.SQLiteConnection(txtConnSqlite.Text)
Dim FirstIndex As Int32 = txtConnSqlite.Text.IndexOf("Data Source=")
If FirstIndex = -1 Then MsgBox("ConnectionString is incorrect", MsgBoxStyle.Exclamation, "Sqlite") : Exit Sub
Dim SecondIndex As Int32 = txtConnSqlite.Text.IndexOf("Version=")
If SecondIndex = -1 Then MsgBox("ConnectionString is incorrect", MsgBoxStyle.Exclamation, "Sqlite") : Exit Sub
Dim FilePath As String = txtConnSqlite.Text.Substring(FirstIndex + 12, SecondIndex - FirstIndex - 13)
If Not IO.File.Exists(FilePath) Then MsgBox("Database file not found", MsgBoxStyle.Exclamation, "Sqlite") : Exit Sub
Try
conn.Open()
Dim cmd As New System.Data.SQLite.SQLiteCommand("SELECT * FROM sqlite_master WHERE type='table';", conn)
Dim reader As System.Data.SQLite.SQLiteDataReader
cmd.ExecuteReader()
MsgBox("Success", MsgBoxStyle.Information, "Sqlite")
Catch ex As Exception
MsgBox("Connection fail", MsgBoxStyle.Exclamation, "Sqlite")
End Try
End Using
I think you can easilly convert it to c# code
This is specific to .NET Core.
Entity Framework Core 5.0 will throw this exception:
System.ArgumentException: Connection string keyword 'failifmissing' is not supported. For a possible alternative, see https://go.microsoft.com/fwlink/?linkid=2142181.
The alternative is to use Mode=ReadWrite in the Connection String.
string connectString = "Data Source=DbFileName.sdb; Mode=ReadWrite;";
ReadWriteCreate - Opens the database for reading and writing, and creates it if it doesn't exist. This is the default.
ReadWrite - Opens the database for reading and writing.
Refer the alternative link provided in the Exception message - https://go.microsoft.com/fwlink/?linkid=2142181
Types of Connection Mode - https://learn.microsoft.com/en-us/dotnet/standard/data/sqlite/connection-strings
Don't catch at that level. Instead, SQLiteConnection should implement IDisposable, meaning you should just return the open connection and allow calling code to handle any exceptions, as well as rely on the Dispose method to close the connection.
If there is no way to change the default SQLite behavior, then you might have to do a File.Exists. That would be better than connecting and creating a new file, checking to see if it's the database you want, then deleting the new file in the catch block.