how to read the connection string from App.config file by C# - c#

I'm using this code to read the connection string from my app.config file but it always return a null value. My App.config file is under my project. Both methods are resulting null values:
public SqlConnection getConnection()
{
try
{
// connectionString = ConfigurationManager.AppSettings["dbConn"];
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
connectionString = System.Configuration.ConfigurationManager.AppSettings["dbConn"];
sqlConnection = new SqlConnection(connectionString);
sqlConnection = new SqlConnection(connectionString);
}
catch (Exception ex)
{
}
return sqlConnection;
}
This is my app.config file declaration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
</configuration>

I think your problem that you try to read connection string twice, first you do it right, and second time you do it wrong, so just remove second line:
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
sqlConnection = new SqlConnection(connectionString);
ConfigurationManager.AppSettings used to access <appSettings>...</appSettings> section of the config.

Can you please try
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
<appSettings>
<add key="dbConn" value="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</appSettings>
</configuration>
Then use the second method.
Make sure you select the App.Config file in the solution explorer and in the property window select Copy to Output Directory to Copy Always. Now Build the application and try again.

You simple define connection string in one class and call that string.....
public class Connection
{
/// <summary>
/// Connection String
/// </summary>
public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
}
}
}
//Returning connction string
sqlConnection conn = new SqlConnection(Connection.ConnectionString);

connectionString=global::myProject.Properties.Settings.Default.myConnectionString

Related

How to pass connectionstring value from Unity3d to a classlibrary with ConfigurationManager

I created a class named "DB" in a ClassLibrary named "DBLayer" to connect a database named "LinguisticsDB". When I implement this ClassLibrary into another project, it can connect its App.config file via "connectionStrings" tag. But I need to access my ClassLibrary from Unity3d help to some kind of file like App.config. I need a step-by-step guide.
On the other hand, I do not know where should I import App.config file?
My DB class into DBLayer:
public static string connectionString = ConfigurationManager.ConnectionStrings["LinguisticsDB"].ConnectionString;
static SqlConnection connection = new SqlConnection(connectionString);
static SqlDataAdapter sqlDataAdapter;
public static DataSet GetData(string query)
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
DataSet dataSet = new DataSet();
sqlDataAdapter = new SqlDataAdapter(query, connection);
sqlDataAdapter.Fill(dataSet);
connection.Close();
return dataSet;
}
My App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="LinguisticsDB" connectionString="Data Source=DESKTOP-NORA1IP; Initial Catalog=Linguistics; Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
I tried to import App.config file into my Unity project inside Scripts folder; but it did not work.
I solved my problem using static connection string. This is awful but it worked.
I changed this
public static string connectionString = ConfigurationManager.ConnectionStrings["LinguisticsDB"].ConnectionString;
to this
public static string connectionString = #"Data Source=.; Initial Catalog=myDatabase; Integrated Security=True;"

What is wrong in the following connection string?

I am trying to create page in asp.net page and I am getting the following error
Error:-System.NullReferenceException: Object reference not set to an instance of an object. at TestdateAssistor.user_info.Button1_Click1(Object sender, EventArgs e)
at this line
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\SQLEXPRESS;Integrated Security=True"].ConnectionString);
This is my complete code
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
conn.Open();
String insert = "insert into Table (NAME,ADDRESS,MOBILE NO,ADHAR NO,DOB) values (#name,#add,#mob,#adhar,#dob)";
SqlCommand com = new SqlCommand(insert,conn);
com.Parameters.AddWithValue("#name",TextBox1.Text);
com.Parameters.AddWithValue("#add",TextBox2.Text);
com.Parameters.AddWithValue("#mob",TextBox3.Text);
com.Parameters.AddWithValue("#adhar", TextBox4.Text);
com.Parameters.AddWithValue("#dob", TextBox5.Text);
com.ExecuteNonQuery();
Response.Write("Successful Registration!!");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:-" + ex.ToString());
}
What changes should I make in the connection string?
You’re using the connection string as a key to your connection strings defined in the Web.config. So you need to define the connection string there and give it a name, then reference it in the code by name:
Web.config:
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True" />
</connectionStrings>
Code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
The ConnectionStrings is a collection automatically built for you by the framework. Its content is retrieved from the web.config where you should have it defined in the proper section.
Then you retrieve its value passing the Name between the square brackets not the whole connectionstring.
string cnString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(cnString);
and in your web.config you add the proper definition for your connectionstring
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
.....
</configuration>
Error:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
Solution 1:
in main program (.cs)
SqlConnection conn = new SqlConnection("Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True");
Solution 2:
in web.config
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
</configuration>
in main program (.cs)
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;);
reference: https://msdn.microsoft.com/en-us/library/d7469at0(v=vs.110).aspx

log4net SQL configuration instead of web.config

Need to have log4net configuring with sql in my project , but due to security reasons must not have the connection string details on the web.config . What are the alternatives ? Just need to hide the ConnectionString only .
{
var settings = ConfigurationManager.ConnectionStrings[1];
var fi = typeof(ConfigurationElement).GetField("_bReadOnly",
BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(settings, false);
string connection = GetConnection();//To get the connection
details using a service
settings.ConnectionString = connection;
}
This is not solving my issue , hiding the connection string
details . The connection details to be pass to the web.config to consume the log.net sql logging
Finally, the one which helped me to pass the connection information to ado.net appender
public static class LogConfigurator
{
public static void SetConnectionString(string connectionString)
{
Hierarchy logHierarchy = log4net.LogManager.GetRepository() as
Hierarchy;
if (logHierarchy == null)
{
throw new InvalidOperationException
("Can't set connection string as hierarchy is null.");
}
var appender = logHierarchy.GetAppenders()
.OfType<AdoNetAppender>()
.SingleOrDefault();
if (appender == null)
{
throw new InvalidOperationException
("Can't locate a database appender");
}
appender.ConnectionString = connectionString; // Using a service to get
//the connection information
appender.ActivateOptions();
}
}
web.config , give the same name for ado.net appender to take the connection
<connectionStringName value="ConnectionString" />
<connectionStrings>
<add name="ConnectionString" connectionString=""
providerName="System.Data.SqlClient" />
</connectionStrings>
You could store the connection string in a separate file which you can keep out of source control to avoid exposing the credentials. Add the following to your Web.config file:
<configuration>
<connectionStrings configSource="connections.secret.config" />
</configuration>
Then create a connections.secret.config file, but keep it away from your solution:
<connectionStrings>
<add name="connection_name" connectionString="your_connection" providerName="System.Data.SqlClient" />
</connectionStrings>
You will need to make sure you provide the connection string wherever you end up deploying your code using an environment variable or similar.

ASP.NET - System.NullReferenceException: Object reference not set to an instance of an object

I created a project in my laptop and it was working fine.
I transferred my project to another laptop and now it gives me a System.NullReferenceException error.
Somehow, the database doesn't establishes, it gives a NULL exception.
My code:
public partial class registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// error is here
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["registerationConnectionString"].ConnectionString);
conn.Open();
string chekuser = "select count(*) from userdata where uname='" + TextBoxUN.Text + "'";
SqlCommand com = new SqlCommand(chekuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exist: ");
}
conn.Close();
}
}
}
WEB.CONFIG
<configuration>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
</configuration>
You don't have any connection string at web.config file with name = registerationConnectionString thus ConfigurationManager.ConnectionStrings["registerationConnectionString"] gives us null value and then when we want to get ConnectionString of null, it gives us System.NullReferenceException. You can resolve this by adding following portion in web.config.
<connectionStrings>
<add name="registerationConnectionString"
connectionString="Data Source=YourServerName;
Initial Catalog=YourDatabaseName;
Persist Security Info=True;
User ID=yourUserId;
Password=yourPassword" />
</connectionStrings>
Since the error is occuring on this line:
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings
["registerationConnectionString"]
.ConnectionString);
You should assume that the ConfigurationManager.ConnectionStrings is null, and look for your configuration file that was probably not correctly copied over. When you attempt the .ConnectionString from the index accessor of the .ConfigurationManager.ConnectionStrings it returns null as you have not configured one in your web.config. Look in web.config for the connectionStrings portion.
Update
Since you have provided the web.config simply add the connectionStrings as desired:
<configuration>
<connectionStrings>
<add name="registerationConnectionString"
connectionString="Data Source=.;Initial Catalog=DBNAME;Integrated Security=True;Connect Timeout=15;" />
</connectionStrings>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
</configuration>

How can I connect C# with Db with App.config?

I need to connect C# with SQL Server database using app.config.
My code is:
public partial class Form1 : Form
{
string connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
public Form1()
{
InitializeComponent();
}
public void InsertDeleteUpdate(string query)
{
try
{
SqlConnection Conn = new SqlConnection(connectionString);
Conn.Open();
SqlCommand comm = new SqlCommand(query, Conn);
comm.ExecuteNonQuery();
Conn.Close();
MessageBox.Show("Succeeded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and in app.config I have:
<connectionStrings>
<add name="Test1"
providerName="System.Data.SqlClient"
connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
</connectionStrings>
but I get an error and I can't fix it:
ConfigurationErrorExeption was Unhandled Configuration system
failed to initialize
Can anyone help me please ?
Try:
var connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;
You're referencing Conn as the connection string name but referenced it as Test1 in the App.Config
Try this..
<connectionStrings>
<add name="Conn" providerName="System.Data.SqlClient"
connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
</connectionStrings>
Try below code and then check
string connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;

Categories

Resources