Storing and Fetching Database Connection Strings from App.config/Web.config File in .NET

It is highly recommended to keep the connection strings of a Database in a separate configuration file so that you can change database connection related information such as password or database name without even modifying or recompiling your source code.

Storing database connection strings in source code can lead to security issues as sensitive information like Username and Passwords are available in the code and it can also cause maintenance problems like you change the password of your DB and then you need to change it everywhere in your code.

.NET Framework has a separate configuration file in both Windows Forms Application (App.config) and ASP .NET Web Application (Web.config). Developers can use this file’s configuration section to store connection string information such as a connection string name or provider type etc.

How to store connection strings in App.config/Web.config file

Open App.config/Web.config, inside the <configuration> element write the code as below


<connectionStrings>
    <add name="SqlServer"
     providerName="System.Data.SqlClient"
     connectionString="Data Source=PCName-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True;"+
     "UserId=username;Password=password" />

    <add name="Oracle"
       providerName="System.Data.OracleClient"
       connectionString="Data Source=localhost;Initial Catalog=Test;Integrated Security=True;"+
       "UserId=username;Password=password" />
  </connectionStrings>

Using the add element you can add connectionStrings to your App.config/Web.config file. You can add Connection Strings of as many databases as you want. Here we have added a connection string for Oracle and Sql Server.

How to retrieve connection string information in .NET Application using C#.

After saving the connection string in App.config/Web.config file you can use System.Configuration.ConfigurationManager class to read this connection string in code.

For that add a reference of System.Configuration.dll in your project.

Right Click on References->Add Reference.

Select .NET Tab. Find System.Configuration there. Click on OK.

The reference should get successfully added to your project.

Now add the namespace using System.Configuration in your code.

Till now probably you have been creating a Connection like this, hardcoding the connection string in your code files.


SqlConnection conn = new SqlConnection("Data Source=PCName-PC\\SQLEXPRESS;UserId=username;Password=password;" +
          "Initial Catalog=Test;Integrated Security=True");

Change the above code with the code below.


public static string cnString = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;
SqlConnection conn = new SqlConnection(cnString);

or use

public static ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["SqlServer"];

public static string connString = conSettings.ConnectionString;

SqlConnection conn = new SqlConnection(connString);

The ConnectionStringsSettings class provides properties to read connection string settings in your program as following code shows.


string name = conSettings.Name;
string providerName = conSettings.ProviderName;
string connString = conSettings.ConnectionString;

That’s it. This is the easy way to save your connection strings at one place and freedom from several maintenance problems.

.NET Project Demonstrating MVC Pattern using C# – Contact Information Management System(CIMS)-Part 7 Viewing All Contacts

Viewing all Contacts

When the user clicks on File->View All->Contacts, then we are opening another Form called ViewAllContacts.cs.

This form contains a DataGridView Control which will display all the contacts of the user.

The DataGridView control gets populated when the Form gets loaded and displays all the existing contacts of the user.

When the user clicks on a Contact in DataGridView Control, it gets selected and displayed in the group box below. Make the DataGridView control read only so that user can’t change any data there and change the SelectionMode property to FullRowSelect

ViewAllContacts

Here’s the code for ViewAllContacts.cs.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CIMS.BO;
using CIMS.BL;

namespace CIMS.UI
{
    public partial class ViewAllContacts : Form
    {
        public ViewAllContacts()
        {
            InitializeComponent();
        }

        private void ViewAllContacts_Load(object sender, EventArgs e)
        {
            List<ContactBO> lstContactDetails = new List<ContactBO>();

            lstContactDetails = ContactBL.GetAllContactDetails();

            dataGridViewContactDetails.DataSource = lstContactDetails;
        }

        private void dataGridViewContactDetails_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Making the labels controls Visible which will display the Search Result
            labelContactIdResult.Visible = labelNameResult.Visible = true;
            labelMobileNumResult.Visible = labelEmailIdResult.Visible = true;
            labelDOBResult.Visible = true;

            labelContactIdResult.Text = dataGridViewContactDetails.SelectedCells[0].Value.ToString();

            string sFName = dataGridViewContactDetails.SelectedCells[1].Value.ToString();
            string sLName = dataGridViewContactDetails.SelectedCells[2].Value.ToString();

            sFName = sFName.Trim();
            sLName = sLName.Trim();
            labelNameResult.Text = sFName + " " + sLName;

            labelMobileNumResult.Text = dataGridViewContactDetails.SelectedCells[3].Value.ToString();
            labelEmailIdResult.Text = dataGridViewContactDetails.SelectedCells[4].Value.ToString();
            labelDOBResult.Text = dataGridViewContactDetails.SelectedCells[5].Value.ToString();

            linkLabelEdit.Visible = true;
            linkLabelDelete.Visible = true;

        }

        private void linkLabelEdit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            EditContact frmEditContact = new EditContact();
            frmEditContact.textBoxContactId.Text = labelContactIdResult.Text;
            frmEditContact.ShowDialog();
        }

        private void linkLabelDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Int32 iContactId = Convert.ToInt32(labelContactIdResult.Text);

            DialogResult result1 = MessageBox.Show("Are you sure you want to delete this Contact?",
                                  "Delete the Contact",
                                   MessageBoxButtons.YesNo);

            if (result1 == DialogResult.Yes)
            {
                int result = ContactBL.RemoveContact(iContactId);

                if (result > 0)
                {
                    MessageBox.Show("Contact Removed Successfully");
                }
            }
        }

    }
}

Here’s the GetAllContactDetails method in ContactBL.


 #region GetAllContactDetails Method
        public static List<ContactBO> GetAllContactDetails()
        {
            List<ContactBO> lstContactDetails = new List<ContactBO>();
            lstContactDetails = ContactDL.FetchAllContactDetails();
            return lstContactDetails;
        }
        #endregion

This method called a method in ContactDL called FetchAllContactDetails. This method connects to the Database and returns a list which contain the ContactBO objects.


  #region FetchAllContactDetails Method
        public static List<ContactBO> FetchAllContactDetails()
        {
            List<ContactBO> lstContactDetails = new List<ContactBO>();

            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM contact_details", conn);

                SqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    lstContactDetails.Add(
                          new ContactBO()
                          {
                              ContactId = Convert.ToInt32(rdr["ContactId"].ToString()),
                              FirstName = rdr["FirstName"].ToString(),
                              LastName = rdr["LastName"].ToString(),
                              MobileNumber = rdr["MobileNumber"].ToString(),
                              EmailId = rdr["EmailId"].ToString(),
                              DOB = Convert.ToDateTime(rdr["DOB"].ToString())

                          }
                      );

                }
                rdr.Close();
                conn.Close();

                return lstContactDetails;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion

Snapshots of Viewing all Contacts

User select File->View All->Contacts

1GoToViewAllMenuItem

A new Form opens called ViewAllContacts appears.  The DataGridView control gets populated when the Form gets loaded and displays all the existing contacts of the user.

When the user clicks on a Contact in DataGridView Control, it gets selected and displayed in the group box below.

2ViewAllContactsFormOpen

And with that we come to the end of Insert, Update Delete Procedure using MVC architecture in .NET in C# Programming Language.

Hope you now have the basic understanding of how to work with MVC Pattern. :D

Multiplication Table in PHP taking Number and Limit from another Form and CSS Styling

Here the user will enter the number and the limit upto which he wants the table, based on that the Multiplication Table of that number gets generated.

We need to create a HTML Form where the user will enter the values.

MultiplicationTableForm.html

<html>
<head>
<title>Multiplication Table Generator Form</title>

<style type="text/css">
table.tab
	{
	border: 1px solid blue;
	text-align: center;
	border-collapse:collapse;
	background: #E0FFFF;
   }

tr.head{font-family: Tahoma,Arial; font-size: 15pt; font-style: normal; font-weight:; color: white;
text-align: center; background-color:#00CED1}

tr.bod{font-family:Tahoma, Arial; font-size: 11pt; font-style: normal; font-weight: ; color:black}

input.sub{font-family:Tahoma, Arial; font-size: 12pt; font-style: normal; font-weight: ; color:black}
</style>

</head>
<body>
<br /><br />
<form name="MultiTableForm" method="POST" action="MultiTable.php">

	<table border='0' width='400' cellspacing='10' cellpadding='05' align='center' class='tab'>
		<tr class='head'>
			<td colspan='2' align='center'>Multiplication Table Generator<br /><br /></td>
		</tr>

		<tr class='bod'>
			<td>Number:</td>
			<td><input type="text" name="num" id="num" />1-100</td>
		</tr>

		<tr class='bod'>
			<td>Upto:</td>
			<td><input type="text" name="upto" id="upto" />1-100</td>
		</tr>

		<tr>
			<td colspan='2' align='center'><br /><br />
			<input type="submit" name="submit" value="Submit" class='sub' />&nbsp;&nbsp;
			<input type="reset" name="reset" value="Reset Fields" class='sub' />
			</td>
		</tr>
	</table>
</form>

</body>
</html>

Snapshot of the Form

MultiTableHTMLForm1

The PHP File will take the values and generate the Form. Appropriate validations are performed here.

MultTable.php

<html>
<head>
<title>Multiplication Table</title>

<style type="text/css">
	/*Style for Table*/
	table
	{
	border-collapse:collapse; width:0%;
	}

	td
	{
	height:35px;
	}
	/*Style for Table Header*/
	td.head{font-family: Tahoma; font-size: 15pt; font-style: normal; color: white;
    text-align: center; background: #00CED1;}

	/*Style of other Table Elements*/
	table, th, td
	{
	font-family:Tahoma, Arial; font-size:11pt;
	color:black; font-style: normal; font-weight: normal;
	border: 1px solid blue;
	text-align: center;
	}

</style>

</head>

<body>

<?php

$num = $_POST['num'];
$upto = $_POST['upto'];

$errorFlag = 0;
$errorString = "Invalid Arguments: <br />";

if ($num <1 || $num >100) {
		$errorFlag = 1;
		$errorString = $errorString." - Number should be between 1 to 100 <br />";
	}
	if ($upto < 1 || $upto > 100) {
		$errorFlag = 1;
		$errorString = $errorString." - Limit should be between 1 to 100";
	}

if ($errorFlag == 0) {

echo "<table align='center'>";

echo "<tr>";
echo "<td colspan='5' class='head'>
		Multiplication Table of $num upto $upto
	</td>";
echo "<tr>";

for($i=1; $i<=$upto; $i++)
{
	if($i%2 == 0)
	{
		echo "<tr bgcolor='PowderBlue'>";
	}

	else
	{
		echo "<tr bgcolor='LightCyan'>";
	}

	echo "<td>$num</td>";

	echo "<td>x</td>";

	echo "<td>$i</td>";

	echo "<td>=</td>";

	echo "<td>".$num*$i."</td>";

	echo "</tr>";

}//for loop ends

echo "</table>";
}

else
{
  echo "<div align='center'>";
  echo "$errorString";
  echo "<br /><br /><br />";
  echo "<a href='MultiTableForm.html'>Back</a>";
  echo "</div>";
}
?>

</body>

</html>

Snapshot of the o/p

User enters the number and limit upto which he wants a Table

MultiTableHTMLForm

Multiplication Table gets generated.

MultiTableGenerated

So Here it comes. Very Useful Program for any School kid. :D and a great learning tool for PHP Beginners. :D