Cannot access connection string in app.config by using c# - c#

App.config file configuration 1
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=223.29.207.133;
Initial Catalog=MBV5DBLive;User ID=smsuser;Password=sms;IntegratedSecurity=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
App.config file configuration 2
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=localhost;
Initial Catalog=University;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
C# code
try
{
String constring = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
}
}
catch (Exception ex)
even if i debug when it comes to configuration manager code will jump to catch block and it will show "Object reference not set to an instance of an object."
What is the issue with above both configuration files?

Your connection string name seems like c_str not MyDBConnectionString.
And since you don't have any MyDBConnectionString in your web config, your ConfigurationManager.ConnectionStrings["MyDBConnectionString"] returns null and that's why you get NullReferenceException when you try to access ConnectionString property of a null reference.
If everything is okey other than that, this should work;
var constring = ConfigurationManager.ConnectionStrings["c_str"].ConnectionString;
using (var con = new SqlConnection(constring))
{
}

Related

connectionString c# doesn´t works

I have a problem withthe connectionString I think.
I have this:
public List<Usuario> getUsuario()
{
List<Usuario> usuarios = new List<Usuario>();
string strConn = ConfigurationManager
.ConnectionStrings["BDLocal"]
.ConnectionString;
using (SqlConnection conn = new SqlConnection(strConn))
and in the web.config:
<connectionStrings>
<add
name="BDLocal"
connectionString="Data Source=DESKTOP-EJ\SQLEXPRESS;Initial
Catalog=Crud.Data;Persist Security Info=True;User
ID=user;Password=pass"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
But the message I get when I go to api/usuario is:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.
I know there must be something I'm doing wrong but I don´t know what it is.

Get connectionString for current DB

I'm trying to find out connectionString which would be like: TestDB.Properties.Settings.TestDBConnectionString (according to this video), but I'm working with WPF and there is no <connectionStrings> in App.config.
I looked at properties of my DB and there was Connection String such as Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=//path_to_file//TestDB.mdf;Integrated Security=True - but it's not the same type was mentioned above. And it won't work for my connection below.
I'm trying to connect like this:
public partial class MainWindow : Window
{
string connectionString;
public MainWindow()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["data_here"].ConnectionString;
}
What you are looking for are ApplicationSettings.
You could create thos via RightClick on your WPF-Project->Add-> Application Settings.
In there you can add ConnectionStrings
You could use it like this:
string con = YourProjectNamespace.Properties.Settings.Default.YourSettingsPropertyKey;
OR
you add them manually to your app.config-file:
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="NameOfConnectionString" connectionString="actualConnectionString" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
You can access them like this:
string appName = "YourAppName.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
string x = section.ConnectionStrings["nameofyourConnectionstring"];
If you need help creating working connectionstrings visit ConnectionStrings.com

connection.open hanging/freezing. What is wrong with my connection string?

I wanted to make my connection string dynamic so I don't have to recompile my code for each new user.
my old connection string:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Storm\documents\visual studio 2015\Projects\SeaSideBlissVersion2\SeaSideBlissVersion2\ShopDb.mdf";Integrated Security=True
My config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="ConnString"
connectionString="Data Source=.;Initial Catalog=ShopDB;Integrated Security=True"/>
</connectionStrings>
</configuration>
and then some code in my db class:
class DB
{
static string conn;
static SqlConnection _conn;
public DB()
{
conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
_conn = new SqlConnection(conn);
}
public void dbAddItem(string name, string measurement, string PLU)
{
string query = string.Format("INSERET INTO tblItems (ItemName, Measurement, Stock, PLUNumber) VALUES ({0}, {1}, {2}, {3})", name, measurement, 0, PLU);
_conn.Open();
SqlCommand comm = new SqlCommand(query, _conn);
comm.ExecuteNonQuery();
_conn.Close();
}
}
And used the following references:
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
When I call my dbAddItem method it seems to hang at _conn.Open()
I'm assuming there's something wrong with my connection string? I've looked it up and nothing that I found helped.
Seems The mistake was obvious, once I put my .mdf db into the debug folder it worked. It makes sense because there is no "exact" directory to look in.
It seems that you missed login info to the DB in the connection string.
Something like "uid=xxx;pwd=xxx".

Using a connection string in a app.config file in a .cs file

I've got a connection string to my database in a my app.config file. I want to using the app.config file rather than copying and pasting the string in the section i want to use it is.
My app.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="|DataDirectory|\SVN .mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and my .cs file is currently like this:
private void sendToDB_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=username;" +"password=password;server=serverurl;" + "Trusted_Connection=yes;" + "database=database; " + "connection timeout=30");
}
I know that this is wrong but want to use the config file instead.
Can anyone help me in how I would go about doing this.
var connectionString=ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
Note : try to keep the name of the connectionstring simpler for readability purposes.
Also,Your assembly also needs a reference to System.Configuration.dll
If you want to access the ConnectionStrings property of your application-configuration file, you have to ...
add a reference to the System.Configuration-dll.
add this to the top of the file:
using System.Configuration;
Then you can access it in this way:
string conStr = ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
using(var con = new SqlConnection(conStr))
{
// ...
}

Null reference exception in asp .net

we are working on a project in which we need to show places on google map. For places, we are providing latitude and longitude from database. we are facing null reference exception error in the following place:
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"].ConnectionString))
How to resolve this error please guide me.
Cause of Exception:-
When you say:
System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"]
Since there is no connection string with name Data Source=KhUSHAL.., thus ConnectionStrings will return null and on that you are trying to access ConnectionString property which will result in Null reference exception. Read about this error here.
Basically you are mixing both, either do this:-
string CS ="Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;Integrated Security=True";
using (SqlConnection con = new SqlConnection(CS))
{
//Your code
}
Or fetch it from Web.Config(Preferred way):-
First define the connection in Web.Config:
<connectionStrings>
<add name="Test" connectionString="Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Then read it like this:-
using (SqlConnection con = new SqlConnection(System.Configuration
.ConfigurationManager.ConnectionStrings["Test"].ConnectionString))
{
//Your code
}
Do you have the ConnectionString in the Web.Config of the UI project?
Fix:
Copy that ConnectionString and Paste in your Web.Config
Your code,
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"].ConnectionString))
is Invalid, this is not the way to declare connection string and access them.
How can we declare Connection Strings and can Access them??
No1:>In a Page
string strConnectionString="server=localhost;database=myDb;uid=myUser;password=myPass;;
Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
}
No2.>Web.Config you can declare then under configuration and appSeting
And Can Access Like:
using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings("myConnectionString")))
{
}
No3>Web.Config you can declare then under configuration and connectionStrings
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
And Can Access Like:
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
}

Categories