I have a problem. I am trying To extract a connection string through
sqlConnStr = new qlConnection(ConfigurationManager.ConnectionStrings["PlacementConnectionString"].ConnectionString);
but it keeps failing :
Object Ref not set to an instance of an object
I check with the debugger and this is the value of the connectionStr
{Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Placement.accdb}
I have imported my database through VS2012's DataSet wizard so what am I doing wrong?
PS: I have tested the connection numerous times.
<connectionStrings>
<add name="_201103578_P09.Properties.Settings.PlacementConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\Placement.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
Kind regards
Markus
[UPDATE]
I changed from
sqlAdapter = new SqlDataAdapter();
try
{
sqlConnStr = new SqlConnection(ConfigurationManager.ConnectionStrings["PlacementConnectionString"].ConnectionString);
}
to
sqlAdapter = new SqlDataAdapter();
string s = ConfigurationManager.ConnectionStrings[1].ConnectionString;
try
{
sqlConnStr = new SqlConnection(s);
}
I inspect s and the value is
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Placement.accdb
Now an error is thrown
System.ArgumentException: Keyword not supported: 'provider'
At wits' end;
=================================================================
TO EVERYONE - THANK YOU the problem was (I forgot) when using an Access database you have to use OleDbCommand and not SqlCommand. Thank you everything works fine now! – Markus just now edit
Going off the code you posted, the only explanation I can see is that the null reference you're getting is related to the configuration manager not getting anything by the string you're passing it.
if
ConfigurationManager.ConnectionStrings["PlacementConnectionString"]
doesn't return anything-- calling
.ConnectionString
will fail with your error. Can you verify that
"PlacementConnectionString"
is the correct name of the connection?
Your connectionstring name is incorrect
<connectionStrings>
<add name="_201103578_P09.Properties.Settings.PlacementConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\Placement.accdb"
providerName="System.Data.OleDb" />
Instead it should be
<connectionStrings>
<add name="PlacementConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\Placement.accdb"
providerName="System.Data.OleDb" />
Or in your code you should look for
ConfigurationManager.ConnectionStrings["_201103578_P09.Properties.Settings.PlacementConnectionString"].ConnectionString
Related
I have my connection string set up in the app config but I can not get it to find that connectionstring or even see that the connection name currency is in the collection.
I tried to add a version.
I have tried to adding the provider name to the string.
I have moved it in and out and in again of the path where the database and solution are located.
I have carefully made sure that I was pointed to the right location on my computer.
<connectionStrings>
<!-- CHANGE THIS to match where your solution and sqlite database are -->
<add name="currency" connectionString="Data Source=F:\CurrencyExercise\currency.db" />
</connectionStrings>
And then the code that calls the above.
public BaseDataAccess(string connectionName = "currency")
{
_connectionName = connectionName;
Connection = new SQLiteConnection(ConfigurationManager.ConnectionStrings[_connectionName].ConnectionString);
Connection.Open();
}
I would expect the code to actually pull back a SQLiteConnection object rather than erroring out.
So I'm using a connection string from my app.config file to connect to my database. I also tried to make it more secure, so that my SqlCOnnectionStringBuilder retrieves its info from the app.config file. To give you a better idea of what I mean here's some code:
app.config:
<connectionStrings>
<clear/>
<add name="connection"
connectionString="Data Source=SERVERIP; Initial Catalog=DB;
Port=3306; User ID=USERNAME; Password=PASSWORD;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Method for the connection builder:
private void BuildConnectionString()
{
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["connection"];
if (null != settings)
{
MySqlConnectionStringBuilder builder =
new MySqlConnectionStringBuilder(settings.ConnectionString);
conString = builder.ConnectionString;
}
}
Somehow the user id gets replaced with the name of my computer, which is very wierd since the IP, port and the initial catalog aren't being replaced.
Oh and I followed this handy article here on MSDN.
Can someone please tell me what I'm doing wrong here?
EDIT:
Here is the full error I'm getting:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Host 'nameofpc' is not allowed to connect to this MariaDB server
It seems to me that the problem is that the MariaDB server is only accepting incoming connections from a certain set of hosts. Most likely the server is defaulted to accept only localhost connections. I think that this link might be helpful: https://mariadb.com/kb/en/mariadb/configuring-mariadb-for-remote-client-access/.
When using WPF and entity-framework I have an APP.CONFIG that looks like the following:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="DatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=%APPDATA%\Folder\Database.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
When using this code it always throws the following error:
System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlServerCe.SqlCeException: The path is not valid. Check the directory for the database. [ Path = %APPDATA%\Folder\Database.sdf ]
When I run the path "%APPDATA%\Folder\Database.sdf" from the command prompt it works fine, and if I remove "%APPDATA% and hardcode the path it works fine - so it looks simply like the %APPDATA% is just not being substituted for the actual folder...
Thanks,
As you already reallized, %APPDATA% or any other environtment variables are not replaced with their respective value in connection strings. Environment varialbes are something related to the operating system shell. They work in command prompt because the command prompt explicitly parses the values entered and substitutes environment variables. That's not something that .NET Framwork usually performs.
To achive this, you have to manually provide the value for %APPDATA% (using Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) or Environment.GetEnvironmentVariable("APPDATA")). There are two options:
Change your connection string and use |DataDirectory|:
<connectionStrings>
<add name="DatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\Database.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
(Notice the use of |DataDirectory| in the path to the database file.)
Then provide the value for |DataDirectory| in your application's Main method:
AppDomain.CurrentDomain.SetData("DataDirectory",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
Refer to this MSDN page for more information.
Manually provide the connection string for your ObjectContext class. This way you can parse and change the connection string:
public static string GetConnectionString()
{
var conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseEntities"].ConnectionString;
return conStr.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
And later:
var db = new DatabaseEntities(GetConnectionString());
Or subclass you ObjectContext class and always use the new connection string:
public class MyDatabaseEntities : DatabaseEntities
{
public MyDatabaseEntities()
: base(GetConnectionString())
{
}
public static string GetConnectionString()
{
var conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseEntities"].ConnectionString;
return conStr.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
}
and use the new class anywhere.
I have another option. We don't need to replace anything. I am using below connection string without any replace and it's working fine.
<connectionStrings>
<add name="ProjectManagementDBEntities" connectionString="metadata=res://*/Models.ProjectManagementModels.csdl|res://*/Models.ProjectManagementModels.ssdl|res://*/Models.ProjectManagementModels.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\ProjectManagementDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
Main change is data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\ProjectManagementDB.mdf;integrated security=True;
I hope this will save someone.
You have to replace the %APPDATA% in the code with the relative path -
var connectionString = ConfigurationManager.ConnectionStrings["DatabaseEntities"]
.ConnectionString;
connectionString.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
i use VS2010 + Framework3.5 + Sql Compact in Project. But when I use the SQL Compact. display the following warning:
The specified store provider cannot be found in the configuration, or is not valid.
for get my data from SQLCE:
EFConn conn = new EFConn();
dataGridView1.DataSource = conn.Students.ToList();
its ok. but, for send data:
EFConn con = new EFConn();
Student objstd = new Student();
objstd.Name = "Sheli";
objstd.Family = "Makro";
con.Students....
is no method Sutdents.AddObject
And there is always the following warning:
The specified store provider cannot be found in the configuration, or is not valid.
thanx for help me...
You need to add the connection string to your application xml.
If you change the platform to x86 instead of Any CPU ?
I had this problem and it seemed to come from x64 provider.
verify your string connection
here example
<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="ConsoleApplication1.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=|DataDirectory|\YourDataBase.sdf"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
</configuration>
verify your provider
providerName="Microsoft.SqlServerCe.Client.3.5"
I am developing an asp.net application which I have hosted on an IIS server. To open a connection I use:
SqlConnection con = new SqlConnection("Server = INLD50045747A\\SQLEXPRESS;
Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
con.Open();
Is it possible to store this connection string somewhere so that I don't need to write in every aspx.cs file? I am using MSSQL database.
I'm facing an issue which says:
The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached
I read somewhere which asks me to increase the maximum connection pool to 100. Will it affect the performance of my application?
You probably aren't closing your open connections propertly.
Increasing the "pool size" is like putting a bigger bucket under a waterfall - it will help, but barely.
Try and locate areas where something like this is happening:
con.Open();
Ensure that if it's not in a try/catch, that it is in one, and that it includes a finally statement.
try {
con.Open();
//several other data base releated
//activities
} catch (Exception ex) {
// do something
} finally {
con.Close();
}
Also, to avoid having to use the finally block, you can just wrap the SqlConnection in a using statement.
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["yourKey"].ConnectionString))
{
// write your code here
}
In regards to your question about connection string, yes store it in your web.config
<connectionStrings>
<add name="name" connectionString="Data Source=;Initial Catalog=;User ID=sa;password=;Persist Security Info=True;Connection TimeOut=20; Pooling=true;Max Pool Size=500;Min Pool Size=1" providerName="System.Data.SqlClient"/>
</connectionStrings>
Store it in the web.config file, in the connectionStrings section:
<connectionStrings>
<add name="name"
connectionString="Data Source=;Initial Catalog=;User ID=sa;password=;Persist Security Info=True;Connection TimeOut=20; Pooling=true;Max Pool Size=500;Min Pool Size=1"
providerName="System.Data.SqlClient"/>
</connectionStrings>
And then you will be able to access this in your code...
ConfigurationManager.ConnectionStrings["name"].ConnectionString
you can do using also
it will automatically disposes the object
if you use "using" there is no need of con.close and all
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["yourKey"].ConnectionString))
{
// write your code here
}
Store the connection string in the web.config files. you can find numerous examples. Check this for the properties. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.71%29.aspx
Thanks
Shankar
Use the Help of Both
try
{
con.Open();
}
catch(Exception ex)
{
if(con.State== ConnectionState.Open)
con.Close();
}
finally
{
con.Close();
}
and also add the Connection String in Web.Config, under Configuration. This will help you.
Yes, store it in the web.config file but make sure that if there is an error it doesn't display the content of the web.config file to the user (thus showing the world your password.)
If you use that same connection string in a lot of applications you could consider writing a service to provide the connection strings, that way you only have to change them in one place.
The best option is to use typed settings.
Open your project properties.
Go to Settings tab.
Add new setting, for example MainConnectionString, select setting type (ConnectionString). In the value insert your connection string or hit '...' button to bring a dialog to build connection string.
Now you can reference your connection string in the code like this:
Settings.Default.MainConnectionString
If you open your config file you will see
<configuration>
<connectionStrings>
<add name="WebApplication1.Properties.Settings.MainConnectionString"
connectionString="Data Source=localhost;Initial Catalog=AdventureWorks;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
You can have this connection string
specified:
for one web site in its own web.config.
for a group of web sites
for all web sites on a box: in machine scope web.config.
for all application on a box: in the machine.config.
This can be convenient if you have a lot of applications that connect to the same db and are installed on one box. If db location changes you update just one file machine.config, instead of going to each application's config file.