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
}
Related
Hello there I hope you're having a great time.
I have a question And I will break it down into 3 points:
1: create a class to connect to sql server the connection should be made using sql server authentication.
This class should contain several variables for connection parameters.
2: create a user form that shows the current connection parameters. And allow the user to update those parameters. In this form there should be a button to test the connect and another button to save the user changes to the connection parameters.
3: how to share the connection, created by the class we made in point 1, between different forms in the application. Without keeping too many open connections ideally only one connection should be open.
I will add the code that can solve this problem I hope that you can help me refine it.
I am new to all of this.
Thank you all for help.
already exists; SqlConnection and maybe SqlConnectionStringBuilder
that kinda already exists, via the IDE, but last time I checked this was not a redistributable dll. You could, however, simply hook a SqlConnectionStringBuilder to a PropertyGrid - or just write the UI from scratch
even "only one connection should be open" is wrong, IMO - let the inbuilt connection pooling deal with that; all you need is some configuration class with the connection string - and just deal with the connections as you need them, very locally - i.e.
using(var conn = new SqlConnection(Config.ConnectionString))
{
conn.Open();
// NOT SHOWN: do a couple of related operations
} // <== and here, it dies
1 : go to MSDN website you'll find what you need :
http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlcommand.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
2: look at your connection properties (http://msdn.microsoft.com/en-us/library/System.Data.SqlClient.SqlConnection_properties.aspx) and fill a listView or equivalent with it
3: Use previous SqlConnection.Open() to deal with it
I'm attempting to do a very basic connection to a sqlite v3 database and I'm using monodevelop 3.0 and Mono 2.10 and am unable to get connected to the database. I can make the app create the database, but then it immediately fails attempting to connect to it. Any suggestions? I had started with a different database, but then decided to have my app attempt to create a database empty and then connect to it. This still seems to fail.
SqliteConnection.CreateFile("db\\DataWorksProg.s3db");
SqliteConnection conn = new SqliteConnection("Data Source=file:db\\DataWorksProg.s3db");
conn.Open();
This small piece of code fails with an error about not being able to open the database file.
Mono.Data.Sqlite.SqliteException: Unable to open the database file
Permissions look OK and I have the Sqlite3.dll in the project, and it seems to be working OK. Have I missed anything obvious? I'm pretty good on the Visual Studio side, but still fairly fresh working in a Mono/Monodevelop environment.
What platform?
I don't believe you need to create a file. If it's not found, iirc, it'll make the database file.
Fwiw, on a Mac, I'm doing (note URI to a pretty standard path; I haven't used Data Source)...
using System;
using System.Data;
using Mono.Data.Sqlite;
namespace test
{
class MainClass
{
public static void Main (string[] args)
{
IDbConnection conTemp = null;
IDbCommand cmdTemp = null;
conTemp = (IDbConnection)new SqliteConnection ("URI=file:/Users/userName/mnmh.db");
conTemp.Open ();
cmdTemp = conTemp.CreateCommand ();
cmdTemp.CommandText = "SELECT * FROM employee";
IDataReader drTemp = cmdTemp.ExecuteReader ();
while (drTemp.Read()) {
Console.WriteLine (drTemp.GetString (0));
}
}
}
}
etc etc
Check the obvious -- you've referenced all the stuff you're using, etc.
Figured out my problem here. Apparently instead of using
"Data Source=file:db\\DataWorksProg.s3db"
I should have been using
"URI=file:db\\DataWorksProg.s3db"
Switched to the URI and it works as expected. I had thought from reading the docs that under the 2.0 profile, the DataSource part was needed instead of the URI, but I got the results I'm looking for.
I'm learning how to work with Oracle and am using C#/Visual Studio. Just as a reference, I'm following this simple tutorial, and have all the prerequisites done (database installed and ODAC with dev tools installed). The following code that's supposed to create an object for connection to a database throws an exception saying "Object reference not set to an instance of an object." and points to 'conn' when I try to run the program:
OracleConnection conn = new OracleConnection ();
The same thing happens regardless of whether I pass the connection string as a parameter or not. I have the needed Oracle.DataAccess reference set, so I don't know if I could be missing something else?
The database is installed and works, but that shouldn't have to do anything with this problem.
I remember having difficulties getting the Oracle Data Provider up and running with C# at first too. My tnsnames.ora file exsted in C:\oracleInstallDir\10.2.0\client_1\NETWORK\ADMIN directory.
My tnsnames.ora looked like this:
XE=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))
Make sure that you have the Oracle.DataAccess reference added to your C# project.
Then also make sure that you are
using Oracle.DataAccess.Client;
public class OracleMgr{
public OracleMgr(){
string connectionStr = "Data Source=XE;User Id=user1;Password=abc";
OracleConnection conn = new OracleConnection(connectionStr);
do stuff...
}
}
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();
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.