I'm trying to create a simple WPF application. I would like the application to indicate if it is not connected to the database, so that it cannot send requests and perform a check of its connection. Simply throw and catch the exception, which will be printed on the screen
My IsConnected
method:
public static bool IsConnected(SqlConnection conn)
{
bool isConnected = false;
try
{
if (conn == null)
{
throw new ConnectionException("It is not possible to connect to the database. Please check your settings and try again");
}
else
{
isConnected = true;
}
}
catch (ConnectionException ex)
{
MessageBox.Show(ex.Message);
}
return isConnected;
}
Where I am using this IsConnected()
method:
public User UserLogin(string email, string password)
{
query = @"SELECT * FROM [User] WHERE email = @email AND password = @password";`
User user = null;
try
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
if (DatabaseSingleton.IsConnected(conn))
{
using (SqlCommand command = new SqlCommand(query, conn))
{
conn.Open();
command.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = email;
command.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = password;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
user = new User
{
Id = reader.GetInt32(0),
Name = reader.GetString(1),
Second_name = reader.GetString(2),
Email = reader.GetString(3),
Password = reader.GetString(4),
User_type = (Type_Of_User)Enum.ToObject(typeof(Type_Of_User), reader.GetInt32(5))
};
}
reader.Close();
}
}
}
}
catch (InvalidInput e)
{
MessageBox.Show(e.Message);
}
return user;
}