C# Web API connectionstrings web.config not being read - c#

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.

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.

Connection string updated on server when publishing

i'm trying to get my connection string values updated on production server during publish. I'm trying the following with no results:
<connectionStrings>
add name="DataConnect" connectionString="Server=Pepe;Database=Oyeti;Integrated Security=SSPI;" xdt:Transform="Replace" />
and also added the xdt:Locator, but i don't think it's the correct way:
<connectionStrings>
add name="DataConnect" connectionString="Server=Pepe;Database=Oyeti;Integrated Security=SSPI;" xdt:Transform="Replace" xdt:Locator="Match(name)" />
What i'm not seeing there?
thanks!
You can add the xdt:Transform="SetAttributes" xdt:Locator="Match(name) attributes to the connectionString tag in your transformation file (Web.Release.config) to transform the values in your primary config file (Web.config). As an alternative, you can also specify connection strings in your publish profile.
Although the default transform file contains an example that shows how
to update a connection string, in most cases you do not need to set up
connection string transformations, because you can specify connection
strings in the publish profile. You'll do that in the deploy to IIS
and deploy to production tutorials.
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/deployment/visual-studio-web-deployment/web-config-transformations

Entity Framework in user control error

I'm using EF for my LiveCharts inside a user control but I'm getting an error
No connection string named 'KiculoServerEntities' could be found in the application config file.
I managed to fix it once after I deleted and create a new EF but after I restarted VS this error showed again,
<add name="KiculoServerEntities"
connectionString="metadata=res://*/KiculoCraftModel.csdl|res://*/KiculoCraftModel.ssdl|res://*/KiculoCraftModel.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-1281SGB;initial catalog=KiculoServer;persist security info=True;user id=KicuCrafts;password=admin;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
Be sure to put that line under:
<configuration>
<connectionStrings>
<!-- here put your connection string -->
</connectionStrings>
...
</configuration>
Connection String Must be available in Caller Project for e.g. If you have Project A and B. Where A is UI and B is EF project, make sure you have Connection String in Project A too
Or if you can shared Context Class and How did u call it in a project like using Startup.cs

Get connection string from app.config

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" />

Reading Hibernate Properties from Web.config

The C# project I'm working on uses nHibernate and the connection string is in the web.config as a property of a Hibernate element. I need to read the connection string in the installer to get a connection manually without using Hibernate. I know I can use configManager.connectionStrings, but as the connection string is already defined in the Hibernate portion of web.config I don't want to copy it again into the connectionStrings element. So how can I access this?
You could put the connection string in the <connectionStrings /> section of the web.config and then have NHibernate get it from there. In the NHibernate settings, remove the <connection.connection_string> property and replace it with <connection.connection_string_name> supplying the name from the <connectionStrings> section. See here for details.
<hibernate>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect"/>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<add key="hibernate.connection.connection_string" value="${local}"/>
</hibernate>
<connectionStrings>
<add name="local" connectionString="server=(local);database=db;Uid=username;Pwd=password;"/>
</connectionStrings>
This makes it available in your ConfigurationManager, but only referenced once.

Categories

Resources