Get connection string from app.config - c#

I'm trying to make this simple call:
DataContext dc = new DataContext(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString)
And here's my app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="MyDB" connectionString="Server=STEVEN-PC;Database=MyDB;Trusted_Connection=yes;" />
</connectionStrings>
</configuration>
But I'm getting an error: Object reference not set to an instance of an object.
It can't find the connection string. What am I doing wrong?

A common mistake is trying to read a connection string from an app.config from a referenced project instead of from the executable project (the web site or .exe project). You may need to copy the config settings containing the connection string to your main config file.

Double check the existence and contents of your configuration file in the build directory. That code should work fine if the config file is in place.
You could also pull put the connection string into a local variable so you can be sure the null reference exception is happening where you think it is.

You might need to specify the providerName:
<add name="MyDB" connectionString="Server=STEVEN-PC;Database=MyDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient" />

Related

ConfigurationManager throwing null exception when trying to read connection string in .NET 4.0

I am working on .NET Framework 4.0 Class Library project along with ADO.NET. I have connectionString inside the App.config which I am trying to read using ConfigurationManager but getting null reference exception.
Error
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name ="dbConnection" connectionString="Data Source=xyz;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Reading ConnectionString
using System.Configuration;
var x22 = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
in app config
<connectionStrings>
<add name="[name]" connectionString="[YOUR CONNECTION]" />
</connectionStrings>
call your connectionString
ConfigurationManager.ConnectionStrings["name"].ConnectionString
In your solution explorer and under reference node, check if assembly System.Configuration has been added related to you needed Configuration Class and there is not any error regarding to your references.
But, your code is correct and I suggest to you try to avoid this error by checking null situation in return value of that command. Maybe config file is not exist in your default path. check config file to be exist then try to read it's data.

C# Web API connectionstrings web.config not being read

This is my first question here, so please be gentle (and provide constructive criticism as to how I can improve my question) :)
I'm trying to connect to an Oracle Database in my Web API project.
This project has an app.config and a web.config.
I don't know why I have both, but it came with that when setting up the (empty asp.net with Web API) project.
This is my code to connect to the database and get the connection string, which is also where I get the NullReferenceException:
// create a connection to the database
using (var con = new OracleConnection(ConfigurationManager.ConnectionStrings["Oracle"].ConnectionString))
And I have included the appropriate using-statements:
using Oracle.ManagedDataAccess.Client;
using System.Configuration;
using System.Data;
using Oracle.ManagedDataAccess.Types;
My web.config file is as follows:
<configuration>
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<!-- Customize these connection alias settings to connect to Oracle DB -->
<dataSource alias="ALIAS" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=IPOFSERVER)(PORT=PORTOFSERVER))(CONNECT_DATA=(SERVICE_NAME=SERVICENAME)));User Id=USERNAME;Password=PASSWORD;" />
</dataSources>
</version>
</oracle.manageddataaccess.client>
<connectionStrings>
<clear/>
<add name="Oracle" connectionString="Data Source=ALIAS;" providerName="Oracle.ManagedDataAccess.Client"/>
</connectionStrings>
</configuration>
Things I've tried so far:
Using System.Web.Configuration.WebConfigurationManager instead
Checking references etc.
Adding AppSettings key and value and try to read that from the web.config file. Also returns null.
I'm not getting any errors other than the runtime NullReferenceException.
I hope this is enough information to suggest a solution. If not, please let me know and I'll provide extra info.
Try the following. It is within System.Configuration:
var con = ConfigurationManager.ConnectionStrings["Oracle"].ConnectionString;
Also, you may want to try without the clear/> in your config.
I've only used an app.config file when I have a console application project in my solution for testing. I store my connection strings in the web.config like so:
<connectionStrings>
<add name="NAME" connectionString="Server=Server;Initial Catalog=TABLE_NAME;User ID=ID;Password=PASSWORD;Application Name='WEBSITE'" />
</connectionStrings>
Then I reference it in my code like so:
protected const string ConnectionString = #"NAME";
Turns out it was a very simple fix, as is usually the case.
As mentioned I have an app.config AND a web.config.
In the web.config are the Oracle Client settings, so because of that and prior experience I figured the connection string should be there too.
When defining it in the app.config however, it works!
Confusing with 2 config files though, as one would expect a connection string to be defined in a web.config, not app.config.
Bottom line: ConnectionStrings should be in the app.config.
That fixed it for me.

C# Connection String Write-Read .ini

I want to write and read my connection string in the Baglanti.cs class, but I don't know anything about this. I trying this first time. I search on Google, but I can't find any clear information.
The .NET way of doing this is using app.config file instead of .ini file
Create a new Application Configuration File with the following content
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="YourConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Retrieve the connectionString inside your application using
var connection = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Check out MSDN: Connection Strings and Configuration Files

Error: Configuration system failed to initialize

Used console application and I have a problem on the app.config file. By right, the code should be correct according to the various sources found in the Internet but my coding is not working for no reason. Anyone can advise me on this?
And the <configuration> appears to be underlined with wriggly blue line, is it a warning or something? I dont know why it appears like this.
[EDITED]
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSetting></configSetting>
<connectionStrings>
<add name="Production"
providerName="System.Data.SqlClient"
connectionString="Data Source=EBSDLAB1SERVER2;Initial Catalog=Production;Integrated Security=True"/>
</connectionStrings>
</configuration>
The error shows, Unhandled Exception: System.Configuration.ConfigurationErrorException:Configuration system fail to initialize ---
System.Configuration.ConfigurationErrorException: Unrecognized configuration section connectionstring
Configuration system failed to initialize
In your App.Config file you need a section for connection strings, it should look like:
<connectionStrings>
<clear />
<add name="Production"
providerName="System.Data.ProviderName"
connectionString="ConnectionStringGoesHere" />
</connectionStrings>
There's more information regarding this here.
I managed to solve this problem which is to copy the app.config file to the same folder as the console application.exe and rename the app.config file according to the console application.exe!
Thank you all for the help!

Dynamic sql connection string

I am using my SQL connection in my mvc4 application as follows:
public static string ConnectionString=#"Data Source=LocalDB)\v11.0;AttachDbFilename=C:\Users\..\Documents\Visual Studio 2012\Projects\..\..\App_Data\RoDB.mdf;Integrated Security=True";
I want to rewrite it as dynamically.
When I change the system, I don't want to change the connection string.
If you use ".\SQLExpress" as server name it will connect to the local instance. In that case you don't need to change your connection string on different machines.
You can put connection strings in your web.config file, this means it is out of application code and doesn't require a re-build to change.
<configuration>
<!-- Other config settings -->
<connectionStrings>
<add name="localDBConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\..\Documents\Visual Studio 2012\Projects\..\..\App_Data\RoDB.mdf;Integrated Security=True" />
</connectionStrings>
</configuration>
Then to use this in your application you can put the following in compiled code:
string myConnectionString = ConfigurationManager.ConnectionStrings["localDBConnection"].ConnectionString;
Whats wrong with using a web config? its pretty much standard practice I'd assume?
Also read up on using the relative path. EG. Relative to application location
add a app configuration file in you application and add setting inside it
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=LocalDB)\v11.0;AttachDbFilename=C:\Users\..\Documents\Visual Studio 2012\Projects\..\..\App_Data\RoDB.mdf;Integrated Security=True"/>
</appSettings>
</configuration>
in your code you can write
string ConnectionString= System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString();

Categories

Resources