Get connection string using app.config file in C# - c#

I want to get connection string using app.config file
this is my app.config file :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MSSConStr"
connectionString="Data Source=Sithi-PC;Initial Catalog=mssdb2;User ID=XXXXX;Password=YYYYYYY"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
string x = ConfigurationManager.ConnectionStrings["MSSConStr"].ConnectionString;
this statement gives a exception "Object reference not set to an instance of an object."
Please can u help me to correct this error!!! this is working properly in .NET framework 3.5 project. But this project is .NET framework 4.0. I added the reference "System.Configuration" to my project and use it in my Database Access class.
Thank you!!!
EDIT: Addional Code:
public static SqlConnection getNewConnection()
{
string x = ConfigurationManager.ConnectionStrings["MSSConStr"].ConnectionString.ToString();
con2 = new SqlConnection(x);
return con2;
}

There are two possible issues:
1) You have some settings elsewhere in the app (settings, code, etc, that is unintentionally clearing the connection strings (unlikely, but possible).
2) The .config that is being used at run time does not have the connection string propagated to it. If you are running in debug mode, open windows explorer, navigate to the bin/debug directory and open the .exe.config or .vshost.exe.config file and see if the connection string is set correctly there. If it isn't, stop the application, clear the directory, and try again. If the problem persists, see item #1.

Related

Formatting MySQL initialization string? [duplicate]

I have an ASP.Net MVC application which runs fine on my local development machine. But when deployed to IIS7 gives the following error when trying to log in:
Format of the initialization string does not conform to specification
starting at index 0
Most people who post this error resolve it by changing their connection string in some way. However my connection string on the local and deployed application are the same. The connection string is like this:
<add name="ApplicationServices" connectionString="Data Source=*server*\*instance*;Initial Catalog=*database*;Integrated Security=True;"
providerName="System.Data.SqlClient" />
What is causing this error in my case?
Format of the initialization string does not conform to specification
starting at index 0
Web.config :
<connectionStrings>
<add name="TestDataConnectionString" connectionString="Data Source=.\SQLExpress;Initial Catalog=TestData;User ID=satest;Password=satest"
/>
</connectionStrings>
In aspx.cs Page the code must be written in the below format :
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["TestDataConnectionString"].ToString());
Web Deployment tool created wrong line in config when I checked Enable CodeFirst Migrations check-box.
In my case I accidentally wrote "password:" instead of "password=" in my conn string
Check to make sure the credentials are correct for the connection string in Web.config. Mine was missing the password for the account with permissions to the database.
I encountered the same error. In my case it was the config transform not working properly.
There is an issue with config transforms when it comes to connection strings.
Some reference:
MSBuild web.config transforms not working by drneel
Replaceable token issue with config ConnectionString transforms by Francis
Also one can write the code in the aspx.cs page as
using (IDbConnection dbConnection =
new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
{
// TODO: Write SQL Stored Procedures or SQL Statements using Dapper
}
For those who would like to find out more about Dapper.
Hope this helps.
If you have been using the Visual Studio Publish Wizard for deployment and checked the Execute Code First Migrations check box in Settings, a new ConnectionString is automatically added to the Server Web.config file, similar t to the 2nd line below:
<add name="LCWeb3Context" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=LCWeb3;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\LCWeb3.mdf" providerName="System.Data.SqlClient" />
<add name="LCWeb3Context_DatabasePublish" connectionString="LCWeb3Context_DatabasePublish.ConnetionString" providerName="System.Data.SqlClient" />
First, notice the added connection string contains "ConnetionString": I think it should be "ConnectionString"! But that's not the solution.
To avoid the "Format of the initialization string does not conform to specification starting at index 0" error, do the following in the Publish Wizard:
In the Settings, select Configuration: Release
In the Settings,don't forget to paste your Connection String in the
"Remote Connection String" field
In the Settings, check Execute Code First Migrations
When doing the above, the connection string added to the Server Web.config reads:
<add name="LCWeb3Context_DatabasePublish" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LCWeb3.mdf;Initial Catalog=LCWeb3;Integrated Security=True" providerName="System.Data.SqlClient" />
and the "Format of the initialization string does not conform to specification starting at index 0" error no longer occurs.
I has the same issue, when I use command: "Update-Database" in Package Manager Console.
To Fix, make sure set startup project to the project which you want to do update.
E.g. I got Db project and Web project, make sure set startup project on Db project, when run "Update-Database", otherwise, it will try to search inside Web project.
The permissions on the SQL server were not correctly set up. I have now resolved this by properly setting up the server permissions.

setup and deployment with database

I want to create an exe of my c# windows application project. I created the exe. But my problem is that I don't know how to include database with this exe. Because now am taking backup of my database and restore this backup to the system in which I want to install my exe. Database is created in sql server2012.
In my c# code connection string set to my system server name. so if I want to install it in another system, I need to change this connection string as server name of the system in which I want to install my exe. But it is not possible in all the time. so is there any method to done all these without changing in the code? I Created the exe using install shield.
Thanks.
Normally database settings should be configurable i.e. the user sets the settings through the application UI which are then written into a configuration file. If you give the settings through a configuration file with hardcoding, the exe need not be built everytime.
For getting the existing database, your application should be coded to create a blank database if the database in the server doesn't exist. The existing data can be imported through Administrator mode od your application or manually done in the SQL Server.
The following code shows how you can store connection strings in App.config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
</configuration>
Once you have saved your connection string in App.config file you can use System.Configuration.ConfigurationManager class to read this connection string in code.
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];
ConnectionStringsSettings class provides properties to read connection string settings in your program as following code shows.
string name = conSettings.Name;
string providerName = conSettings.ProviderName;
string connectionString = conSettings.ConnectionString;
The above code has been taken from this link
For a detailed example check this article on CodeProject

A database with the same name exists, or specified file cannot be opened, or it is located on UNC share

Getting this error when I run my project in new PC. TO avoid this I have to copy paste the new Connection string every time .. Is there any way to avoid that ... I have 3 different database and its very annoying O_O
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\Yoro\\Desktop\\WAPent 3.0 (1)\\WAPent 3.0\\WAPent 3.0\\WAPent 2.0\\WAPent 2.0\\App_Data\\LoginStuff.mdf;Integrated Security=True;User Instance=True");
Web Config code
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\LoginStuff.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
In the web.config you are using |DataDirectory| which is a substitution for the path to the datadirectory. This is set by using
AppDomain.CurrentDomain.SetData("DataDirectory", newpath)
When you do not set |DataDirectory| it defaults to the App_Data folder when it is a web project.
So looking at your code the path represented by DataDirectory probably does not contain the database file.
For more info about datadirectory have a look at this (older) article.
Open server explorer, right-click on your database, select properties on bottom right corner. A property window will appear; copy the connection string there and use it in your application. For example, in my application:
SqlConnection sconnection = new SqlConnection(#"Data Source=(LocalDB)\v11.0;
AttachDbFilename=C:\Users\Taha\Documents\Visual Studio 2013\Projects\Finder\Finder\App_Data\Userdb.mdf;
Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");
sconnection.Open();
This issue generally occurs in VS 2012 which I too have faced it.
In order to resolve it,you need to foolow these steps:
1)Right Click on the .mdf file ->Select Modify connections under server Explorer.
2)Popup window will come->Click Advanced Button ->Select (LocalDB)\v11.0 as DataSource value
Also make sure you make changes in webconfig file as well for DataSource=(LocalDB)\v11.0
You are done.Wella!!
First, your Database must be in other location than bin folder from your project;
Then, your connection must be declared like this:
SqlConnection con = new SqlConnection(TABLE1TableAdapter.Connection.ConnectionString);
If you have a DataGridView you can click on Choose Data Scource, and add your table as source from your database.(In my example, the table is named TABLE1.) Then, visual studio automatly create a DataSet, DataBinding, and a TableAdapter. The TableAdapter (TABLE1TableAdapter) contains as property the ConnectionString you need for database.
P.S. I had this problem, and after a lot of work, i find this solution. I hope it helps you too.
You should check your connection string. when you try to attach sql file the connection string should be like that:
DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|PharmacyDB.mdf;Database=PharmacyDB;Integrated Security=True
I get this error when I use two connection string in my same DBContext,for example I try to Connect to sql server in a connection string and connect to sql express file in another connection string:
public MyDBContext(bool autoDetectChangesEnabled)
: base("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\MyDB.mdf;User Instance=false;Integrated Security=True;MultipleActiveResultSets=True")
{
Initialize(autoDetectChangesEnabled);
}
public MyDBContext()
: base("data source=(LOCAL)\\SQLEXPRESS;initial catalog=MyDB;persist security info=True;user id=user;password=pass;MultipleActiveResultSets=True;App=EntityFramework")
{
Initialize(true);
}
Realizing I'm resurrecting an old topic, but my search led me here and the solution that worked for me was not covered in the responses.
I'm using an mdf file as my project's database and by using the Server Explorer in VS I was accurately building my connection string with the following:
string _connectionString = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename={System.IO.Directory.GetCurrentDirectory() + "\\Database.mdf"};Integrated Security=True";
Seemed correct, but I was still receiving this same error. After some trial and error, I found that the issue was not the connection string, but rather the mdf file properties. The setting "Copy to Output Directory" was set to "Do not copy" initially. Setting this to "Copy if newer" fixed the issue for me.
In my case, I just clean the solution and then rebuild it. It works well.
Exit Visual Studio.
Run Visual Studio again.
Do not open your project from last program list, open it using the open project -> browse procedure.
Go to server explorer: if your .mdf file icon has a little red X, then create a new table, no need to enter anything in the table. Just update it.
First you will see a prompt: choose NO.
In the second prompt, choose YES: the little red X should go away.
Delete the table you just created and update.
This solved the problem for me.

MetadataException - Unable to load the specified metadata resource?

I have a solution with two relevant projects. The first builds My.exe, and the second builds a class library MyModel.dll that contains only my EF model.
I'm getting a MetadataException in my Model's VS-generated ObjectContext ctor. I've read through Troubleshooting Entity Framework Connection Strings, but I still haven't been able to narrow down my problem.
The offending constructor code:
public MyEntities() :
base(#"name=MyEntities", "MyEntities") // MetadataException here
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
Metadata Artifact Processing is set to EmbedInOutputAssembly. When I open MyModel.dll in Reflector, I see:
DataAccessLayer.MyModel.csdl
DataAccessLayer.MyModel.msl
DataAccessLayer.MyModel.ssdl
I've tried setting Build Action for my app.config to None and Content, and neither makes a difference. The config file contains:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyEntities"
connectionString="metadata=
res://*/DataAccessLayer.MyModel.csdl|
res://*/DataAccessLayer.MyModel.ssdl|
res://*/DataAccessLayer.MyModel.msl;
provider=Devart.Data.PostgreSql;
provider connection string="
User Id=MY_USER;
Password=MY_PASS;
Host=127.0.0.1;
Database=MY_DB;
Persist Security Info=True""
providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
I've tried replacing the resource prefix res://*/ with both res://MyModel.dll/ and res://MyModel/, leaving the rest intact (because it matches the resources in MyModel.dll), but neither solved the problem. My class library is strong-named.
Both my executable and class library projects contain references to System.Data.Entity and Devart.Data.PostgreSql, and My.dll is being built to the same location as My.exe.
I stepped into .NET source code, and by examining the arguments & local variables of internal EF calls, found the resource assembly name was still set to *.
It turns out a bug in my application code set the model's default connection string before calling the ObjectContext ctor. It was pulled from a Settings.settings file, which hadn't been recently sync'd with the latest, correct app.config.
Some reflections on our discussion in the comments:
The correct assembly name in app.config is MyModel rather than MyModel.dll (as shown in Craig's article.) Using MyModel.dll produces an exception in the EF code.
Calling the ctor as base(#"name=MyEntities") instead of base(#"name=MyEntities", "MyEntities") actually produced a new exception in ObjectContext.GetEntitySetName()
I updated Settings.settings to be in sync with app.config, and everything is now working.

ConfigurationManager keeps getting Machine.config connection string

I have a c# assembly that uses the app.config to store its database connection string. When debugging the application I noticed that the connection to the database kept failing because the ConfigurationManager kept returning the machine.config connection string:
data source=.\SQLEXPRESS; Integrated Security;....
I added <clear/> before my connection string in the app.config and it fixed the issue on my dev machine. The problem returned when I deployed it to production. Can someone tell me how I can stop the machine.config connection string from being used?
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
<connectionStrings>
<clear/>
<add name="VersionConnectionString"
connectionString=" Data Source=localhost;Initial Catalog=VersionInfo;User ID=user;Password=password"
providerName="System.Data.SqlClient" />
</connectionStrings>
UPDATE
The following still gives me the machine.config connection string?!
Configuration appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
string dllConfigData =
appConfig.ConnectionStrings.ConnectionStrings[0].ConnectionString;
When using connection strings in a DLL, you need to add them to your exe's app.config as well, using the exact same name for the setting. Then, you can change the connection string in the exe's .config file and the DLL will pick it up automatically when loaded.
This is probably the only way you can have working custom connection strings in the app.config file when your DB persistence layer is implemented in a separate DLL. Don't even ask me how much time it took me to research and debug this.
I know this is an older question, but I was having the same problem today. The problem was that the app.config that I added to my project wasn't being copied to the output directory. To fix this, right click on the app.config and select Properties. Then change Build Action to Content.
Hope this helps!
Try getting an instance of your app.config file as a Configuration object:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var myConnString = config.ConnectionStrings["VersionConnectionString"].ConnectionString;
This bypasses the machine config file completely.
You should be getting your connection string by NAME instead of INDEX - that will ensure you're getting what you're asking for.
Try
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["VersionConnectionString"].ConnectionString);

Categories