c969-project/C969Project/Data/DatabaseHelper.cs
2025-06-26 21:02:53 -05:00

695 lines
28 KiB
C#

using MySql.Data.MySqlClient;
using C969Project.Data.Models;
namespace C969Project.Data;
public static class DatabaseHelper
{
private static string ConnectionString => AppSettings.GetSetting("ConnectionStrings", "DefaultConnection");
public static User? Login(string username, string password)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
}
catch (MySqlException ex)
{
MessageBox.Show($"Database connection error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
string query = "SELECT * FROM client_schedule.user WHERE userName = @username";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@username", username);
using MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string name = reader.GetString("userName");
string pass = reader.GetString("password");
if (name == username && password == pass)
{
int id = reader.GetInt32("userId");
return new User(id, name);
}
}
return null;
}
public static List<User> RetrieveUsers()
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
}
catch (MySqlException e)
{
MessageBox.Show($"Database connection error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return new List<User>();
}
List<User> users = new List<User>();
using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.user", connection);
using MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var user = new User(reader.GetInt32("userId"), reader.GetString("userName"));
users.Add(user);
}
return users;
}
#region Customers
public static List<Customer> RetrieveCustomers()
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
}
catch (MySqlException e)
{
MessageBox.Show($"Database connection error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return new List<Customer>();
}
List<Customer> customers = new List<Customer>();
using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.customer", connection);
using MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var customer = new Customer()
{
CustomerId = reader.GetInt32("customerId"),
CustomerName = reader.GetString("customerName"),
AddressId = reader.GetInt32("addressId"),
Active = reader.GetInt32("active"),
CreateDate = reader.GetDateTime("createDate"),
CreatedBy = reader.GetString("createdBy"),
LastUpdate = reader.GetDateTime("lastUpdate"),
LastUpdateBy = reader.GetString("lastUpdateBy"),
};
customers.Add(customer);
}
return customers;
}
public static Customer? RetrieveCustomer(int customerId)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
}
catch (MySqlException e)
{
MessageBox.Show($"Database connection error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
string query = "SELECT * FROM client_schedule.customer WHERE customerId = @customerId";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@customerId", customerId);
using MySqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
return new Customer
{
CustomerId = reader.GetInt32("customerId"),
CustomerName = reader.GetString("customerName"),
AddressId = reader.GetInt32("addressId"),
Active = reader.GetInt32("active"),
CreateDate = reader.GetDateTime("createDate"),
CreatedBy = reader.GetString("createdBy"),
LastUpdate = reader.GetDateTime("lastUpdate"),
LastUpdateBy = reader.GetString("lastUpdateBy"),
};
}
return null;
}
public static int AddCustomer(Customer customer)
{
int customerId = 0;
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query =
"INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy) " +
"VALUES (@customerName, @addressId, @active, @createDate, @createdBy, CURRENT_TIMESTAMP, @lastUpdateBy); " +
"SELECT LAST_INSERT_ID();";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@customerName", customer.CustomerName);
command.Parameters.AddWithValue("@addressId", customer.AddressId);
command.Parameters.AddWithValue("@active", customer.Active);
command.Parameters.AddWithValue("@createDate", DateTime.UtcNow);
command.Parameters.AddWithValue("@createdBy", AppState.CurrentUser.Username);
command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username);
object result = command.ExecuteScalar();
if (result != null && result != DBNull.Value)
{
customerId = Convert.ToInt32(result);
}
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return customerId;
}
public static void UpdateCustomer(Customer customer)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query =
"UPDATE customer SET customerName = @customerName, addressId = @addressId, active = @active, " +
"lastUpdate = CURRENT_TIMESTAMP, lastUpdateBy = @lastUpdateBy WHERE customerId = @customerId";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@customerName", customer.CustomerName);
command.Parameters.AddWithValue("@addressId", customer.AddressId);
command.Parameters.AddWithValue("@active", customer.Active);
command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username);
command.Parameters.AddWithValue("@customerId", customer.CustomerId);
command.ExecuteNonQuery();
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public static void DeleteCustomer(int customerId)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query = "DELETE FROM customer WHERE customerId = @customerId";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@customerId", customerId);
command.ExecuteNonQuery();
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public static void DeleteCustomer(Customer customer)
{
DeleteCustomer(customer.CustomerId);
}
#endregion
#region Addresses
public static Address? RetrieveAddress(int addressId)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
}
catch (MySqlException e)
{
MessageBox.Show($"Database connection error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
string query = "SELECT * FROM client_schedule.address WHERE addressId = @addressId";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@addressId", addressId);
using MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var addr = new Address()
{
Id = reader.GetInt32("addressId"),
Address1 = reader.GetString("address"),
Address2 = reader.GetString("address2"),
CityId = reader.GetInt32("cityId"),
PostalCode = reader.GetString("postalCode"),
Phone = reader.GetString("phone"),
CreateDate = reader.GetDateTime("createDate"),
CreatedBy = reader.GetString("createdBy"),
LastUpdate = reader.GetDateTime("lastUpdate"),
LastUpdateBy = reader.GetString("lastUpdateBy"),
};
return addr;
}
return null;
}
public static int AddAddress(Address address)
{
int addressId = 0;
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query =
"INSERT INTO address (address, address2, cityId, postalCode, phone, createDate, createdBy, lastUpdate, lastUpdateBy) " +
"VALUES (@address1, @address2, @cityId, @postalCode, @phone, @createDate, @createdBy, CURRENT_TIMESTAMP, @lastUpdateBy); " +
"SELECT LAST_INSERT_ID();";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@address1", address.Address1);
command.Parameters.AddWithValue("@address2", address.Address2);
command.Parameters.AddWithValue("@cityId", address.CityId);
command.Parameters.AddWithValue("@postalCode", address.PostalCode);
command.Parameters.AddWithValue("@phone", address.Phone);
command.Parameters.AddWithValue("@createDate", DateTime.UtcNow);
command.Parameters.AddWithValue("@createdBy", AppState.CurrentUser.Username);
command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username);
object result = command.ExecuteScalar();
if (result != null && result != DBNull.Value)
{
addressId = Convert.ToInt32(result);
}
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return addressId;
}
public static void UpdateAddress(Address address)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query =
"UPDATE address SET address = @address1, address2 = @address2, cityId = @cityId, postalCode = @postalCode, " +
"phone = @phone, lastUpdate = CURRENT_TIMESTAMP, lastUpdateBy = @lastUpdateBy WHERE addressId = @addressId";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@address1", address.Address1);
command.Parameters.AddWithValue("@address2", address.Address2);
command.Parameters.AddWithValue("@cityId", address.CityId);
command.Parameters.AddWithValue("@postalCode", address.PostalCode);
command.Parameters.AddWithValue("@phone", address.Phone);
command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username);
command.Parameters.AddWithValue("@addressId", address.Id);
command.ExecuteNonQuery();
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region Appointments
public static List<Appointment> RetrieveAppointments(int? userId = null)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
}
catch (MySqlException e)
{
MessageBox.Show($"Database connection error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return new List<Appointment>();
}
List<Appointment> appointments = new List<Appointment>();
string query = "SELECT * FROM client_schedule.appointment";
if (userId.HasValue) query += " WHERE userId = @userId";
using MySqlCommand command = new MySqlCommand(query, connection);
if (userId.HasValue) command.Parameters.AddWithValue("@userId", userId.Value);
using MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var appt = new Appointment()
{
AppointmentId = reader.GetInt32("appointmentId"),
CustomerId = reader.GetInt32("customerId"),
UserId = reader.GetInt32("userId"),
Title = reader.GetString("title"),
Description = reader.GetString("description"),
Location = reader.GetString("location"),
Contact = reader.GetString("contact"),
AppointmentType = reader.GetString("type"),
Url = reader.GetString("url"),
Start = reader.GetDateTime("start"),
End = reader.GetDateTime("end"),
CreateDate = reader.GetDateTime("createDate"),
CreatedBy = reader.GetString("createdBy"),
LastUpdate = reader.GetDateTime("lastUpdate"),
LastUpdateBy = reader.GetString("lastUpdateBy"),
};
appointments.Add(appt);
}
return appointments;
}
public static void AddAppointment(Appointment appointment)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query =
"INSERT INTO appointment (appointmentId, customerId, userId, title, description, location, contact, type, url, start, end, createDate, createdBy, lastUpdate, lastUpdateBy) " +
"VALUES (@appointmentId, @customerId, @userId, @title, @description, @location, @contact, @type, @url, @start, @end, @createDate, @createdBy, @lastUpdate, @lastUpdateBy)";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@appointmentId", appointment.AppointmentId);
command.Parameters.AddWithValue("@customerId", appointment.CustomerId);
command.Parameters.AddWithValue("@userId", appointment.UserId);
command.Parameters.AddWithValue("@title", appointment.Title);
command.Parameters.AddWithValue("@description", appointment.Description);
command.Parameters.AddWithValue("@location", appointment.Location);
command.Parameters.AddWithValue("@contact", appointment.Contact);
command.Parameters.AddWithValue("@type", appointment.AppointmentType);
command.Parameters.AddWithValue("@url", appointment.Url);
command.Parameters.AddWithValue("@start", appointment.Start);
command.Parameters.AddWithValue("@end", appointment.End);
command.Parameters.AddWithValue("@createDate", DateTime.UtcNow);
command.Parameters.AddWithValue("@createdBy", AppState.CurrentUser.Username);
command.Parameters.AddWithValue("@lastUpdate", DateTime.UtcNow);
command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username);
command.ExecuteNonQuery();
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public static void UpdateAppointment(Appointment appointment)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query =
"UPDATE appointment SET customerId = @customerId, userId = @userId, title = @title, description = @description, " +
"location = @location, contact = @contact, type = @type, url = @url, start = @start, end = @end, " +
"lastUpdate = @lastUpdate, lastUpdateBy = @lastUpdateBy WHERE appointmentId = @appointmentId";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@customerId", appointment.CustomerId);
command.Parameters.AddWithValue("@userId", appointment.UserId);
command.Parameters.AddWithValue("@title", appointment.Title);
command.Parameters.AddWithValue("@description", appointment.Description);
command.Parameters.AddWithValue("@location", appointment.Location);
command.Parameters.AddWithValue("@contact", appointment.Contact);
command.Parameters.AddWithValue("@type", appointment.AppointmentType);
command.Parameters.AddWithValue("@url", appointment.Url);
command.Parameters.AddWithValue("@start", appointment.Start);
command.Parameters.AddWithValue("@end", appointment.End);
command.Parameters.AddWithValue("@lastUpdate", DateTime.UtcNow);
command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username);
command.Parameters.AddWithValue("@appointmentId", appointment.AppointmentId);
command.ExecuteNonQuery();
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public static void DeleteAppointment(int appointmentId)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query = "DELETE FROM appointment WHERE appointmentId = @appointmentId";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@appointmentId", appointmentId);
command.ExecuteNonQuery();
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public static void DeleteAppointment(Appointment appointment)
{
DeleteAppointment(appointment.AppointmentId);
}
#endregion
#region Cities
public static City? RetrieveCity(int cityId)
{
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
}
catch (MySqlException e)
{
MessageBox.Show($"Database connection error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
string query = "SELECT * FROM client_schedule.city WHERE cityId = @cityId";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@cityId", cityId);
using MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var city = new City()
{
CityID = reader.GetInt32("cityId"),
CityName = reader.GetString("city"),
CountryID = reader.GetInt32("countryId"),
CreateDate = reader.GetDateTime("createDate"),
CreatedBy = reader.GetString("createdBy"),
LastUpdate = reader.GetDateTime("lastUpdate"),
LastUpdateBy = reader.GetString("lastUpdateBy"),
};
return city;
}
return null;
}
public static int GetCityId(string cityName, int countryId)
{
int cityId = 0;
try
{
using (MySqlConnection connection = new MySqlConnection(ConnectionString))
{
connection.Open();
string query = "SELECT cityId FROM city WHERE city = @cityName AND countryId = @countryId";
using (MySqlCommand cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("@cityName", cityName);
cmd.Parameters.AddWithValue("@countryId", countryId);
object result = cmd.ExecuteScalar();
if (result != null && result != DBNull.Value)
{
cityId = Convert.ToInt32(result);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Error getting city ID: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return cityId;
}
public static int AddCity(City city)
{
int cityId = 0;
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query =
"INSERT INTO city (city, countryId, createDate, createdBy, lastUpdate, lastUpdateBy) " +
"VALUES (@cityName, @countryId, @createDate, @createdBy, CURRENT_TIMESTAMP, @lastUpdateBy); " +
"SELECT LAST_INSERT_ID();";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@cityName", city.CityName);
command.Parameters.AddWithValue("@countryId", city.CountryID);
command.Parameters.AddWithValue("@createDate", DateTime.UtcNow);
command.Parameters.AddWithValue("@createdBy", AppState.CurrentUser.Username);
command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username);
object result = command.ExecuteScalar();
if (result != null && result != DBNull.Value)
{
cityId = Convert.ToInt32(result);
}
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return cityId;
}
#endregion
#region Countries
public static int GetCountryId(string countryName)
{
int countryId = 0;
try
{
using (MySqlConnection connection = new MySqlConnection(ConnectionString))
{
connection.Open();
string query = "SELECT countryId FROM country WHERE country = @countryName";
using (MySqlCommand cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("@countryName", countryName);
object result = cmd.ExecuteScalar();
if (result != null && result != DBNull.Value)
{
countryId = Convert.ToInt32(result);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Error getting country ID: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return countryId;
}
public static int AddCountry(Country country)
{
int countryId = 0;
using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection"));
try
{
connection.Open();
string query =
"INSERT INTO country (country, createDate, createdBy, lastUpdate, lastUpdateBy) " +
"VALUES (@countryName, @createDate, @createdBy, CURRENT_TIMESTAMP, @lastUpdateBy); " +
"SELECT LAST_INSERT_ID();";
using MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@countryName", country.CountryName);
command.Parameters.AddWithValue("@createDate", DateTime.UtcNow);
command.Parameters.AddWithValue("@createdBy", AppState.CurrentUser.Username);
command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username);
object result = command.ExecuteScalar();
if (result != null && result != DBNull.Value)
{
countryId = Convert.ToInt32(result);
}
}
catch (MySqlException e)
{
MessageBox.Show($"MySQL Error: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"General Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return countryId;
}
#endregion
}