Null reference exception in asp .net - c#

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))
{
}

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.

Error while changing connection string dynamically

I am using ADO.net and my requirement is to change server dynamically based on some condition.
So in my web.config I have saved 2 connections as below. One names REMOTE and DBCS
<add name="REMOTE" connectionString="Server=;Initial Catalog=;Persist Security Info=False;User ID=;Password=;MultipleActiveResultSets=true;Encrypt=True;
TrustServerCertificate=False;Connection Timeout=0" providerName="System.Data.SqlClient"/>
<add name="DBCS" connectionString="Server=;Initial Catalog=;Persist Security Info=False;User ID=;Password=;MultipleActiveResultSets=true;Encrypt=True;
TrustServerCertificate=True;Connection Timeout=0" providerName="System.Data.SqlClient"/>
And below is the if condition that will change the server.
I want to use the same con variable throughout the code.
if (some condition)
{
string connectionString = ConfigurationManager.ConnectionStrings["REMOTE"].ConnectionString;
con = new SqlConnection(connectionString);
}
But while reassigning the new connectionstring to con variable, I am getting error.
Error:
Cannot assign to 'con' because it is a 'using variable'
As I am new to C#, I am having difficult handling this situation.
You (correctly) have the con instance being created in a using block. Pass the correct connection string at the time you create the SqlConnection instance, do not reassign after it is created
string connectionString = (some condition)
? ConfigurationManager.ConnectionStrings["REMOTE"].ConnectionString
: ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using(var con = new SqlConnection(connectionString))
{
// code using your SqlConnection instance
}
It seems you are using a using block and try to assign a new value within that block, which is not allowed.
The documentation states:
Within the using block, the object is read-only and cannot be modified or reassigned.

windows service not add data to database after release

I`m new to ASP.Net and I need to create windows service for adding data to mssql database but the problem is my code is work in visual studio before release after I release its not adding data to database
string strConn = ConfigurationManager.ConnectionStrings["MyDBConfig"].ConnectionString;
SqlConnection oSqlConnection = new SqlConnection(strConn);
oSqlConnection.Open();
string insertText = #"INSERT INTO csvs(Agency,Status) VALUES ('Tst','0')";
using (var command2 = new SqlCommand(insertText, oSqlConnection))
{
command2.ExecuteNonQuery();
}
this is my app.config file
<connectionStrings>
<add name="MyDBConfig" connectionString="Data Source=.\SQLExpress;Initial Catalog=test;Integrated Security=True"/>
</connectionStrings>

Accessing database connection string using app.config in C# winform

I can't seem to be able to access the app.config database connection string in my c# winforms app.
app.config code
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
C# code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["MyDBConnectionString"];
When I try the C# code, I get a message:
Warning 1 'System.Configuration.ConfigurationSettings.AppSettings' is obsolete: '
This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'
However, when I try to use:
conn.ConnectionString = System.Configuration!System.Configuration.ConfigurationManager.AppSettings["MyDBConnectionString"];
I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
This is all you need:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Use ConfigurationManager instead of ConfigurationSettings. It has a ConnectionStrings property that you should use for connection strings in the connectionStrings section:
ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
You are using the ConnectionStrings collection, not the AppSettings.
ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=MY-PC;Initial Catalog=DB2013;User ID=sa;Password=MYSQL123" />
</appSettings>
</configuration>
using System.Configuration;
using System.Data.SqlClient;
namespace OnlineDelete_W2013
{
public partial class CommodityEdit : Form
{
SqlConnection MyConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
public CommodityEdit()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MyConnection.Open();
}
catch (Exception)
{
throw;
}
}
}
}
try this
ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnection"].ToString()))
{
....(your code here) ...
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["MyDBConnectionString"].ConnectionString;
try
{
conn.Open();
}
catch (Exception)
{
throw;
}
The answers stating to use the line
ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
are correct.
If an error appears stating that ConfigurationManager does not exist, it's because your project hasn't referenced System.Configuration.
To do that in .NET Framework, in Solution Explorer, in the project where you want to use this line of code, right-click in References, choose Add Reference..., then choose Assemblies on the left-side and Framework under it. Pick System.Configuration on the list and click Ok.
About this:
I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
I just declared a var like this and solved the problem:
var strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Please try below code. this is as you are expecting:
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

Compiler Error Message: CS0118: 'System.Configuration.ConfigurationManager.AppSettings' is a 'property' but is used like a 'method'

Compiler Error Message: CS0118: 'System.Configuration.ConfigurationManager.AppSettings' is a 'property' but is used like a 'method'
<add key="ObjConn" value="Provider=SQLOLEDB;Persist Security Info=True;User ID=OMembers;PWD=OMembers;Initial Catalog=Db;Data Source=""/>
strconnection = System.Configuration.ConfigurationManager.AppSettings("ObjConn");
sqlcon = new SqlConnection(strconnection);
in C#, do this:
strconnection = System.Configuration.ConfigurationManager.AppSettings["ObjConn"];
sqlcon = new SqlConnection(strconnection);
I believe you're working in C#? You need to access it using index operator:
strconnection = System.Configuration.ConfigurationManager.AppSettings["ObjConn"];
Better to define connection strings in the connection strings section as so:
<connectionStrings>
<add
name="ObjConn"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
And instantiate you SqlConnection like this:
strconnection = System.Configuration.ConfigurationManager.ConnectionStrings["ObjConn"].ConnectionString;
sqlcon = new SqlConnection(strconnection);

Categories