Connection string not found i have tried multiple ways but all goes in vein, i have a data access layer project in app.config i have mention connection string
</configuration>
<connectionStrings>
<add name="MySqlConnectionString" connectionString="server=myserver;User Id=myuser;password=mypassword;database=mydatabase"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
C# Code
public void ConnectionString()
{
try
{
var connectionString = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString; //does not work
var connectionString2 = ConfigurationManager.AppSettings["MySqlConnectionString"];//does not work
}
catch(Exception ex)
{
}
}
What am doing wrong i have try multiple solution it does not work for me
ConnectionString Not Found
Your connection string name is Default. And you should consider this detail when you want to read it. Try like this;
public void ConnectionString()
{
try
{
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
}
catch(Exception ex)
{
}
}
Or you can change connection string name as you wish;
</configuration>
<connectionStrings>
<add name="MySqlConnectionString" connectionString="server=myserver;User Id=myuser;password=mypassword;database=mydatabase"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
From the picture I can see an "app.config" and a "web.config", so I presume there are different projects. Am I right? If it is, you have to add the connectionString on the execution project (if it is a web site, or a standalone, or whatever it is).
The code you were using is correct
var connectionString = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString;
It has to work correctly.
Thanks Every one for helping my the main issue was i have added connectionstring attribute in the wrong place
Wrong place
<runtime>
<connectionStrings>
<add name="MySqlConnectionString" connectionString="server=myserver;User Id=myuser;password=mypassword;database=mydatabse"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</runtime>
</configuration>
Right place i have cut the connection string under the runtime attribute and paste it alone and the issue is solved
<connectionStrings>
<add name="MySqlConnectionString" connectionString="server=myserver;User Id=myuser;password=mypassword;database=mydatabse"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
Thanks everyone
Related
Trying to read the database name but it's not working in the site. Using an asp.net web project with a solution file. I put this in the web.config. This will change depending on development database or production database PRODDB via the web configuration transform files and scripts.
<appSettings>
<add key="databaseName" value="DEVELDB"/>
<add key="operatingEnvironment" value="dev"/>
</appSettings>
Within the Global.asax.cs file:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var operatingEnvironment = WebConfigurationManager.AppSettings["operatingEnvironment"].ToString();
if (operatingEnvironment == "dev")
{
Application["DBE"] = WebConfigurationManager.AppSettings["databaseName"].ToString();
}
}
Within the login.cs class file:
internal static DatabaseConnection GetDatabaseConnection()
{
return
new DatabaseConnection(
new ConnectionProperties
{
User = Shared.User,
Application = Shared.Application,
DatabaseName = (string)HttpContext.Current.Application["DBE"]
});
}
and within the Web.Development.config file there is:
<appSettings>
<add key="databaseName" value="DEVELDB" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<add key="operatingEnvironment" value="dev" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
</appSettings>
However, whenever I debug after login, it goes to the code below which is good (the same as coded above) but says Database name was not specified? I have it specified as DEVELDB and using "DBE" to reference it. However, it's not like it debugs to another area and to there, just straight to there and kills it?
...
{
User = Shared.User,
Application = Shared.Application,
DatabaseName = (string)HttpContext.Current.Application["DBE"]
});
Connections to databases go inside the "connectionstrings" tags in you "webconfig" file. If you need SqlServer it is shown below
<configuration>
<connectionStrings>
<add name="TwoWayConn" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\TwoWayData.accdb"
providerName="System.Data.OleDb" />
<add name="TWOWAYDATASQL" connectionString="Data Source=TBIRD\SQLEXPRESS1;Initial Catalog=TWOWAYDATASQL.MDF;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
</configuration>
Am I misunderstanding what you are trying to do?
I'm new to .NET, but I'm using EntityFramework 5.0 and .NET 4.5
I have a website where the connectionStrings in the web.config are maintained in a configSource as follows:
<connectionStrings configSource="ConfigOverrides\overrideConnectionStrings.config">
</connectionStrings>
My website has modules with nested web.config files. These modules specify their own connectionStrings in the nested web.config. Everything was fine until I put a System.Data.EntityClient connection in my ConfigOverrides\overrideConnectionStrings file. After I did this I would get an error from the module:
No connection string named 'WebsiteEntities' could be found in the application config file.
If I copy the module's connectionString to the one in ConfigOverrides I get an error that there is already a connection string with that name. If I remove the connection string from their nested web.config and just put it in my overrides, it works. However I'm not wanting to maintain all module's connectionSettings in that global override.
Contents of overrideConnectionStrings.config:
<connectionStrings>
<add name="SqlServices" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=my_db;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\my_db.mdf;" />
<add name="TermsEntities" providerName="System.Data.EntityClient" connectionString="metadata=res://*/Terms.csdl|res://*/Terms.ssdl|res://*/Terms.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDb)\v11.0;Initial Catalog=my_db;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\my_db.mdf;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" />
<add name="ADServer" connectionString="LDAP://ldap.localdomain:389/DC=company,DC=com" />
</connectionStrings>
Contents of module's nested Web.config connectionStrings:
<connectionStrings>
<add name="WebsiteEntities" connectionString="metadata=res://*/WSE.csdl|res://*/WSE.ssdl|res://*/WSE.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=WSE_DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="RoutingConn" providerName="System.Data.SqlClient" connectionString="data source=.;initial catalog=WSE_DB;integrated security=True;" />
</connectionStrings>
I should note that the module worked fine until I added my TermsEntities to the main site's web.config (via the ConfigOverrides).
I am still unable to figure out what in my application setup is causing the connectionString to not be found. While debugging I could view the connectionStrings available to the path of the request and I would see all connectionStrings (those in the nested web.config and those in the root web.config).
My workaround is to just use the ConfigurationManager from System.Configuration and read in the connection string :
public partial class WebsiteEntities : DbContext
{
public WebsiteEntities()
: base(ConfigurationManager.ConnectionStrings["WebsiteEntities"].ConnectionString ?? "name=WebsiteEntities")
{
}
...
This seems to be working.
I'm trying to create an ASP.NET website. There I'm using a database. To connect with the database I'm using the connectionstring which I've stored in the web.config file like
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
</connectionStrings>
and at code behind
private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
So you can see the database is stored at G:\path\to\db\CarRentalServiceDB.mdf.
But now if my friend want to take the project from me and try to run the project from his machine then he has to change the connectionString at web.config. Say the website is now at D:\path\to\db\foo\CarRentalServiceDB.mdf in my friend's machine, then the connectionString needs to change. Isn't it tedious?
Is there any way to change the connectionString dynamically with any batch file or code so that it will change with respect to the current directory it is residing now?
You shoud use the |DataDirectory| token: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
You would add multiple connections strings in your web.config file and call the one you need like
Web.config File
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
<add name="DBConnectionStringTwo"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\path\to\db\foo\CarRentalServiceDB.mdf;Integrated Security=True"/>
</connectionStrings>
Code for connection strings
//Connection String 1
private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
//Connection String 2
private string _connectionString2 = ConfigurationManager.ConnectionStrings["DBConnectionStringTwo"].ConnectionString;
Every time I try to run a unit test with some test methods, I get a NullReferenceException at the first line of the following :
public DB()
{
this.sqlConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
this.con = new SqlConnection(this.sqlConnectionString);
this.con.StateChange += new StateChangeEventHandler(this.Connection_StateChange);
}
After further research I realized I should add an app.config file to my test project.
I have no clue what to do with it or what it's used for, though.
Tips on how to proceed?
You need to add a new Connection String section in your app.config with the name ConnectionString (Since that is what you're referencing in your C# code):
<configuration>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=YourDataSource;Initial Catalog=YourDatabase;IntegratedSecurity=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
You will also need to change the actual connectionString value in the app.config file.
If I have several pages what would be the correct procedure in creating a connection string variable and sharing it among all of my pages. I would prefer not to type the connection string 100 times for each page and would just rather call it. Can I create it in my namespace or whats the best approach?
Put the connection string in the web.config file. See the following on MSDN: How to: Read Connection Strings from the Web.config File
Example of connection string in config:
<connectionStrings>
<add name="Movies2"
connectionString="Data Source=(local);Initial Catalog=Movies;User ID=wt3movies;Password=lalalalala;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
Using the string:
string connStr = ConfigurationManager.ConnectionStrings["Movies2"].ConnectionString;
It's typically in your configuration file (web.config)
can't you use the <connectionStrings/> configuration ?
http://msdn.microsoft.com/en-us/library/ms178411.aspx
Well i would have included Setting file and placed it over there.It may be not the best bet but works for me.
There are many options. It depends on what data access methodology you are using. I would suggest creating a class to handle loading the connection string from the web.config file and exposing it as a public property.
There are a variety of ways to approach this which would delve in to architecture/SOC/IoC/Repository/ etc, but to answer your question in its simplest possible sense, you could create a Database class that had a single method that fetched your connection string from configuration.
internal class DataAccess
{
static string GetDatabaseConnection()
{
return ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;
// where AppDb is defined in your web.config/app.config.
}
}
Your pages could just use:
string connection = DataAccess.GetDatabaseConnection();
connection strings are usually stored in configuration files such as the web config. Here is a simple example
add something like this to the config
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
and then retrive it as
System.Configuration.Configuration rootWebConfig =
S
ystem.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
if (connString != null)
Console.WriteLine("Northwind connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No Northwind connection string");
}
full article is here http://msdn.microsoft.com/en-us/library/ms178411.aspx
You should keep it in you config file. For winforms that will be app.config, and for webforms it's web.config. Here is the section you need to have (for winforms).
<connectionStrings>
<add name="MyNameSpace.Properties.Settings.ConnectionString1"
connectionString="Data Source=MYSQLSERVER;Initial Catalog=DATABASENAME;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then you can access the connection string like this (depending on your .NET version - this is for 2.0)
string connectionString = ((string)(configurationAppSettings.GetValue(ConnectionString1"", typeof(string))));
Have the connection string (CS) in (App/Web).Config file and have the CS returned from a static method GetConncectionString().It means, this particular static method would be used in all the pages where CS is required.
You can also make a file called connectionStrings.config,or a name you choose, with this content:
<connectionStrings>
<add name="MyConnection" connectionString="server=MyServer; database=MyDataBase; user id=myUser; pwd=MyPwd;"/>
</connectionStrings>
And then, in your Web.Config
Insert this tag under node
<connectionStrings configSource="connectionStrings.config"/>