I have a bunch of database methods that I normally copy and paste into my aspx code behind files on every web app I build.
That said, I was trying to build my next app by putting all of my connection info and data calls into a class library.
Then compile it as a DLL and reference it in my project. Does this make sense?
The thing I can't work out is in error handling. I usually put the exception message into a label with red font.
But in a library and a method is called which should return a Boolean value, How do I return the error message to the web form?
Here is a sample of what I have.
My aspx page would be requesting the result of validateDomainKey and supplying the string values.Thanks in advance.
using System;
using System.Data.SqlClient;
using System.Data;
namespace MyApp.Data
{
public class Provider
{
private static String _sqlConnDev = @"Data Source=localhost;Initial Catalog=********;Persist Security Info=True;User ID=********;Password=********";
public static String SqlConnDev
{
get
{
return _sqlConnDev;
}
}
public bool validateDomainKey(String lic, String dom)
{
bool result = false;
String connectionString = SqlConnDev;
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand mySqlCommand = new SqlCommand("sp_validateLicense", myConnection);
SqlDataReader MyReader = null;
try
{
if (myConnection.State == ConnectionState.Closed)
{
myConnection.Open();
mySqlCommand.CommandType = CommandType.StoredProcedure;
mySqlCommand.Parameters.AddWithValue("@license", lic);
mySqlCommand.Parameters.AddWithValue("@domain", dom);
MyReader = mySqlCommand.ExecuteReader();
if (MyReader.HasRows)
{
result = true;
MyReader.Close();
}
}
}
catch (SqlException ex)
{
string ErrorMessage = "Could not connect to database: " + ex.Number + " " + ex.Message;
}
finally
{
if (mySqlCommand != null)
{
mySqlCommand.Dispose();
mySqlCommand = null;
}
if (myConnection != null)
{
if (myConnection.State == ConnectionState.Open)
{
myConnection.Close();
}
}
}
return result;
}
}
}