ConfigurationManager ConnectionString not working - c#

I have this project I am working on and I want to "hide" my connection string from my main class and place it to the App.Config.
While trying to access the connection string from the main class I get this error "System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null."
This is my main class code that I use to get the conn string:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString.ToString();
This is my App.Config code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnString" connectionString="Password=XXXX;Persist Security Info=True;User ID=XXXX;Initial Catalog=XXXX;Data Source=XXXX"/>
</connectionStrings>
</configuration>
Note: I have to add the app.config by myself as a new class.
Also the connection string works perfect when it's in the main class, so it's not its fault.

The WebConfig connection string should be like this:
<connectionStrings>
<add name="DBCS" connectionString="server=.;database=MVCCrud;integrated security=SSPI" providerName="Sql.Data.SqlClient" />
</connectionStrings>
The main class connection string should be like this:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

I added config, added you code and configuration and it worked.
I can't add this as a comment, as I can't post images there, that's why I am writing an answer.
So, just to make sure you added the file in a correct way:
right click your project, add -> new item:
and then just find appropriate file to add (you can make use of search text box):

Related

ASP.Net can't see my database from the ISS

I decided to learn how to make a simple ASP.Net project, with a reference to a database project through the Repository Pattern.
I have my Controller calling for a List<Weight> to handle:
public IActionResult MyWeight()
{
var repo = new Database.Repositories.WeightRepository();
var data = repo.GetWeight().Result;
return View(data);
}
When repo.GetWeight() is called, I get an AggregateException error, with an inner exception saying:
"No connection string named 'MyDatabaseConnection' could be found in the application config file."
So for clarity, let me outline the solution's structure:
aspProj
Controllers
Views
Service
App.config (1)
Web.config
...
Database
Entities
Repositories
App.config (2)
...
Database.Test
Test.cs
App.config (3)
...
I've added the following connectionString to all App.configs and the Web.config:
<connectionStrings>
<add
name="MyDatabaseConnection"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
I have tested the database both from Visual Studio's Server Explorer, and through the Test.cs file from the test-project. I can insert data and retrieve without a problem.
But when the ASP.Net-part wants to access it, there is no love.
I thought it might be the ISS which did not know the path from where it is...
Any thoughts?
__
Edit:
My Web.config:
My AppSetting.json:
Well the problem is clear - ASP.NET is trying to access the database using a connection string with the name MyDatabaseConnection:
<connectionStrings>
<add name="MyDatabaseConnection" connectionString="put the connection to the db here..." />
</connectionStrings>
And in your Web.config you only have a connection string with the name WeightDatabaseConnection:
<connectionStrings>
<add name="WeightDatabaseConnection" connectionString="put the connection to the db here..." />
</connectionStrings>
Just add a new element for MyDatabaseConnection under <connectionStrings> in the Web.config file and it should work

Reading connection string from external config file

I have created a console application and an app.config file and Connections.config file.
The app.config file has a connectionstring property source pointing to the Connections.config
When I tried to read the connection string in the application, I get a ConfigurationErrorException
This is my main method.
static void Main(string[] args)
{
var settings = ConfigurationManager.ConnectionStrings;
if (settings != null)
{
foreach (ConnectionStringSettings setting in settings)
{
Console.WriteLine(setting.ConnectionString);
}
}
}
App.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings configSource="Connections.config"></connectionStrings>
</configuration>
Connections.config file
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
Here I observed two things.
First: If I specify configSource I am unable to read the connection string (throwing exception.)
Second: If I put same connection string in App.config file and tried to read then the code is working but getting two connection string (which supposed to be return only one which is empty string)
The first connection string is sqlexpress connection string like this
data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
second connection string it returning is empty string (This is expected).
I want to read connection string from external file like in my scenario. How to do that? What am I missing here?
MSDN says:
Do not include any additional elements, sections, or attributes.
You need to remove the XML encoding.
Edit
Also, you need to set the properties of your config file to Copy to Output Directory = Copy if newer or Copy always.
Edit 2
To build on what Dave said, you add the clear element to your external file. Your final Connections.config file should look exactly like this:
<connectionStrings>
<clear/>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
Your Connections.config file should be as shown below without the xml header
<connectionStrings>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
Also for it to correctly locate the file in your console application, please set the Copy to Output Directory to Copy Always or Copy If Newer.
That first connection string you are getting is inherited from the machine.config. This is described in the MSDN documentation. http://msdn.microsoft.com/en-us/library/bf7sd233(v=vs.90).aspx
You can use the Clear tag in your config file to remove inherited connection strings.
http://msdn.microsoft.com/en-us/library/ayb15wz8(v=vs.90).aspx
<connectionStrings>
<clear/>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
There is a nice article on MSDN: https://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx.
Quote from the article:
To store connection strings in an external configuration file, create
a separate file that contains only the connectionStrings section. Do
not include any additional elements, sections, or attributes. This
example shows the syntax for an external configuration file.
<connectionStrings>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
Hope this helps people who run into this question later.

Getting configuration values rom XML file located in the same project

I am making a little program to copy pictures form one location to another. The information for the pictures are stored in a database so I need connections string and also I create a txt file with the final output from the operation and I want to store these two values in a App.Config.xml file.
The structure of my project is very simple :
And the XML files itself is :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDB" connectionString="Data Source=.\\DVSQLEXPRESS08;Initial Catalog=**;Persist Security Info=True;User ID=**;Password=**;MultipleActiveResultSets=True" />
</connectionStrings>
<createResultFile>
<add key="ResultFile" value="C:\Users\dv\Desktop\Leron\PictureStatus.txt"/>
</createResultFile>
</configuration>
I want to use the connectionString and <createResultFile> value in my PictureTransferTool.cs. This is my first time working with XML file and C# (.NET in general) so I want what is the way to retrieve those config values?
You config file must be like below...
Config File :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ResultFile" value="C:\Users\dv\Desktop\Leron\PictureStatus.txt"/>
</appSettings>
<connectionStrings>
<add name="MyDB" connectionString="Data Source=.\\DVSQLEXPRESS08;Initial Catalog=**;Persist Security Info=True;User ID=**;Password=**;MultipleActiveResultSets=True" />
</connectionStrings>
</configuration>
C# :
You can read Connection String like below
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
Console.WriteLine(connectionString);
You can read User Defined Settings like Below
var Resultfile = System.Configuration.ConfigurationManager.AppSettings["ResultFile"];
Console.WriteLine(Resultfile);
The Way I normally do user-defined parameters in my app.config is i put them in the appSettings tab.
<appSettings>
<add key="myStr" value="String Value" />
and then you can access it with
string myStr = System.Configuration.ConfigurationSettings.AppSettings["myStr"];
It works for me.
Linq;
using System.Xml.XPath;
...
var doc = XDocument.Load("test.xml");// You should put the way to your XML
var name = doc.XPathSelectElements("/configuration/connectionStrings/add").Value;
var name = doc.XPathSelectElements("/configuration/createResultFile/add").Value;

Reading Connection string from application Config file

I am trying to read a connection string from the application configuration file.
But keep receiving an error:
The name ConfigurationManager does in exit in current context.
After googling the error, I added ConfigurationManager to my project. But I still get the same error.
My code:
string sqlConStr = ConfigurationManager.ConnectionStrings["AppConnectionString"].ToString();`
My application config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="AppConnectionString" connectionString="SERVER=1894; Database=db; UID=loss; PWD=where;encrypt=no;enlist=false" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Ensure you have referenced System.configuration.
Then make sure you either import the correct namespace
using System.Configuration;
or use the full typename
string sqlConStr = System.Configuration.ConfigurationManager.ConnectionStrings["AppConnectionString"].ToString();
Try using ConnectionString
var connection = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;

Where to store and how to access a connection string

Where to add the connection string in a C# project? Like this string?
<connectionStrings>
<add name="strConn"
connectionString="Data Source=abc;Password=pass;User ID=user"
providerName="Oracle.DataAccess.Client">
</add>
</connectionStrings>
And how can I call it from my program.cs file?
This will be added in the configuration file. If it is an ASP.NET application, then this would be the web.config file. If it is a Winforms/Console application this would be the app.config file.
To call it from the application, you'd have to use the System.Configuration namespace like so:
using System.Configuration;
string YourConnectionString =
ConfigurationManager.ConnectionStrings["yourConnStringName"].ConnectionString;
Where "yourConnStringName" is the name of your connectionString in your config file.
The connection string like the one you posted is placed in a configuration file called app.config and whenever you want to get a connectionstring you can get it like:
string strConn = ConfigurationManager.ConnectionStrings["strConn"].ConnectionString;
see this
Add it to your app.config under <configuration> and to call it from your program.cs use:
ConfigurationSettings.AppSettings["strConn"]

Categories