We have recently started working in ASP.NET and starting a simple CRUD Web application in ASP.Net. Here is the approach we are following to connect to DB.
Connection.cs
public class Connection
{
public SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CWConnectionString"].ConnectionString);
private readonly log4net.ILog logger = log4net.LogManager.GetLogger("Connection.cs");
public Connection()
{
//
// TODO: Add constructor logic here
//
}
public bool CheckOpenConnection()
{
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
return true;
}
else
{ return false; }
}
catch (Exception Ex)
{
logger.Error("Error in CheckOpenConnection : " + Ex.Message);
return false;
}
}
public void OpenConnection()
{
try
{
if (CheckOpenConnection() == false)
con.Open();
}
catch (Exception Ex)
{
logger.Error("Error in OpenConnection : " + Ex.Message);
}
}
public void CloseConnection()
{
try
{
if (CheckOpenConnection() == true)
con.Open();
}
catch (Exception Ex)
{
logger.Error("Error in CloseConnection : " + Ex.Message);
}
}
}
Then we use some methods like this in another cs file
Dal_authentication.cs
public DataTable AuthenticateUser(string UserName, string Password)
{
try
{
DataTable results = new DataTable();
Connection cn = new Connection();
cn.OpenConnection();
string sql_SP = "uspAuthenticateLogin";
using (SqlCommand cmd = new SqlCommand(sql_SP, cn.con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@UserName", SqlDbType.NVarChar, 50));
cmd.Parameters["@UserName"].Value = UserName;
cmd.Parameters.Add(new SqlParameter("@Password", SqlDbType.NVarChar, 50));
cmd.Parameters["@Password"].Value = Password;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(results);
}
cn.CloseConnection();
return results;
}
catch (Exception Ex)
{
//logger.Error("AuthenticateUser : " + Ex.Message);
return null;
}
}
Is there any flaw in this approach? Is it the right way to connect to DB? Are there any possible improvements?