From d26498cd3ccd7bc86d1e1220a58f8bf9c7172ddd Mon Sep 17 00:00:00 2001 From: Spudnut2000 Date: Mon, 16 Jun 2025 22:33:41 -0500 Subject: [PATCH] ability to add and update customers --- C969Project/AddUpdateCustomerForm.Designer.cs | 25 + C969Project/AddUpdateCustomerForm.cs | 224 ++- C969Project/Data/DatabaseHelper.cs | 1720 +++++++++-------- C969Project/RecordsForm.cs | 2 + 4 files changed, 1119 insertions(+), 852 deletions(-) diff --git a/C969Project/AddUpdateCustomerForm.Designer.cs b/C969Project/AddUpdateCustomerForm.Designer.cs index a6081f6..1ee00d8 100644 --- a/C969Project/AddUpdateCustomerForm.Designer.cs +++ b/C969Project/AddUpdateCustomerForm.Designer.cs @@ -45,6 +45,8 @@ partial class AddUpdateCustomerForm cityTextBox = new System.Windows.Forms.TextBox(); label7 = new System.Windows.Forms.Label(); zipTextBox = new System.Windows.Forms.TextBox(); + label8 = new System.Windows.Forms.Label(); + textBox1 = new System.Windows.Forms.TextBox(); SuspendLayout(); // // label1 @@ -170,12 +172,32 @@ partial class AddUpdateCustomerForm zipTextBox.Size = new System.Drawing.Size(218, 23); zipTextBox.TabIndex = 12; // + // label8 + // + label8.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)0)); + label8.Location = new System.Drawing.Point(236, 299); + label8.Name = "label8"; + label8.Size = new System.Drawing.Size(63, 23); + label8.TabIndex = 15; + label8.Text = "Country"; + label8.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // textBox1 + // + textBox1.Location = new System.Drawing.Point(12, 299); + textBox1.Name = "textBox1"; + textBox1.Size = new System.Drawing.Size(218, 23); + textBox1.TabIndex = 14; + textBox1.Text = "US"; + // // AddUpdateCustomerForm // AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; BackColor = System.Drawing.SystemColors.Control; ClientSize = new System.Drawing.Size(800, 450); + Controls.Add(label8); + Controls.Add(textBox1); Controls.Add(label7); Controls.Add(zipTextBox); Controls.Add(label6); @@ -196,6 +218,9 @@ partial class AddUpdateCustomerForm PerformLayout(); } + private System.Windows.Forms.Label label8; + private System.Windows.Forms.TextBox textBox1; + private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox cityTextBox; private System.Windows.Forms.Label label7; diff --git a/C969Project/AddUpdateCustomerForm.cs b/C969Project/AddUpdateCustomerForm.cs index dfd4ea0..09c0a8b 100644 --- a/C969Project/AddUpdateCustomerForm.cs +++ b/C969Project/AddUpdateCustomerForm.cs @@ -1,44 +1,194 @@ +using System; +using System.Windows.Forms; using C969Project.Data; using C969Project.Data.Models; -namespace C969Project; - -public partial class AddUpdateCustomerForm : Form +namespace C969Project { - public AddUpdateCustomerForm() + public partial class AddUpdateCustomerForm : Form { - InitializeComponent(); + private Customer? _currentCustomer; + + public AddUpdateCustomerForm() + { + InitializeComponent(); + saveButton.Click += SaveButton_Click; + cancelButton.Click += CancelButton_Click; + } + + public void InitAdd() + { + Text = "Add Customer"; + label1.Text = "Add Customer"; + + nameTextBox.Text = string.Empty; + addressTextBox.Text = string.Empty; + cityTextBox.Text = string.Empty; + zipTextBox.Text = string.Empty; + phoneTextBox.Text = string.Empty; + _currentCustomer = null; + + ShowDialog(); + } + + public void InitUpdate(Customer customer) + { + Text = "Update Customer"; + label1.Text = "Update Customer"; + + _currentCustomer = customer; + + nameTextBox.Text = customer.CustomerName; + var addr = DatabaseHelper.RetrieveAddress(customer.AddressId); + if (addr != null) + { + addressTextBox.Text = addr.Address1; + var city = DatabaseHelper.RetrieveCity(addr.CityId); + if (city != null) + { + cityTextBox.Text = city.CityName; + } + zipTextBox.Text = addr.PostalCode; + phoneTextBox.Text = addr.Phone; + } + + ShowDialog(); + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrWhiteSpace(nameTextBox.Text) || + string.IsNullOrWhiteSpace(addressTextBox.Text) || + string.IsNullOrWhiteSpace(cityTextBox.Text) || + string.IsNullOrWhiteSpace(zipTextBox.Text) || + string.IsNullOrWhiteSpace(phoneTextBox.Text)) + { + MessageBox.Show("All fields must be filled out.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + if (!System.Text.RegularExpressions.Regex.IsMatch(phoneTextBox.Text.Trim(), @"^[\d-]+$")) + { + MessageBox.Show("Phone number can only contain digits and dashes.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + + string currentUser = AppState.CurrentUser.Username; + + try + { + + string countryName = "US"; + int currentCountryId = DatabaseHelper.GetCountryId(countryName); + if (currentCountryId == 0) + { + Country newCountry = new Country + { + CountryName = countryName, + CreateDate = DateTime.UtcNow, + CreatedBy = currentUser, + LastUpdate = DateTime.UtcNow, + LastUpdateBy = currentUser + }; + currentCountryId = DatabaseHelper.AddCountry(newCountry); + } + + int currentCityId = DatabaseHelper.GetCityId(cityTextBox.Text.Trim(), currentCountryId); + if (currentCityId == 0) + { + City newCity = new City + { + CityName = cityTextBox.Text.Trim(), + CountryID = currentCountryId, + CreateDate = DateTime.UtcNow, + CreatedBy = currentUser, + LastUpdate = DateTime.UtcNow, + LastUpdateBy = currentUser + }; + currentCityId = DatabaseHelper.AddCity(newCity); + } + + Address addressToSave; + int finalAddressId; + + if (Text == "Add Customer") + { + addressToSave = new Address + { + Address1 = addressTextBox.Text.Trim(), + Address2 = "", + CityId = currentCityId, + PostalCode = zipTextBox.Text.Trim(), + Phone = phoneTextBox.Text.Trim(), + CreateDate = DateTime.UtcNow, + CreatedBy = currentUser, + LastUpdate = DateTime.UtcNow, + LastUpdateBy = currentUser + }; + finalAddressId = DatabaseHelper.AddAddress(addressToSave); + } + else + { + Address? existingAddress = DatabaseHelper.RetrieveAddress(_currentCustomer.AddressId); + if (existingAddress == null) + { + MessageBox.Show("Could not find existing address for update.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + addressToSave = existingAddress; + addressToSave.Address1 = addressTextBox.Text.Trim(); + addressToSave.Address2 = ""; + addressToSave.CityId = currentCityId; + addressToSave.PostalCode = zipTextBox.Text.Trim(); + addressToSave.Phone = phoneTextBox.Text.Trim(); + addressToSave.LastUpdateBy = currentUser; + + DatabaseHelper.UpdateAddress(addressToSave); + finalAddressId = addressToSave.Id; + } + + Customer customerToSave; + if (Text == "Add Customer") + { + customerToSave = new Customer + { + CustomerName = nameTextBox.Text.Trim(), + AddressId = finalAddressId, + Active = 1, + CreateDate = DateTime.UtcNow, + CreatedBy = currentUser, + LastUpdate = DateTime.UtcNow, + LastUpdateBy = currentUser + }; + DatabaseHelper.AddCustomer(customerToSave); + } + else + { + customerToSave = _currentCustomer; + customerToSave.CustomerName = nameTextBox.Text.Trim(); + customerToSave.AddressId = finalAddressId; + customerToSave.LastUpdateBy = currentUser; + + DatabaseHelper.UpdateCustomer(customerToSave); + } + + MessageBox.Show("Customer saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + // TODO: Implement robust exception handling, logging, and user notification as per assignment A2b + MessageBox.Show($"An error occurred while saving the customer: {ex.Message}", "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } } - - public void InitAdd() - { - Text = "Add Customer"; - label1.Text = "Add Customer"; - - nameTextBox.Text = string.Empty; - addressTextBox.Text = string.Empty; - cityTextBox.Text = string.Empty; - zipTextBox.Text = string.Empty; - phoneTextBox.Text = string.Empty; - - ShowDialog(); - } - - public void InitUpdate(Customer customer) - { - Text = "Update Customer"; - label1.Text = "Update Customer"; - - nameTextBox.Text = customer.CustomerName; - var addr = DatabaseHelper.RetrieveAddress(customer.AddressId); - addressTextBox.Text = addr.Address1; - var city = DatabaseHelper.RetrieveCity(addr.CityId); - cityTextBox.Text = city.CityName; - zipTextBox.Text = addr.PostalCode; - phoneTextBox.Text = addr.Phone; - - ShowDialog(); - } - - // name, {address, phone} } \ No newline at end of file diff --git a/C969Project/Data/DatabaseHelper.cs b/C969Project/Data/DatabaseHelper.cs index ddea8a4..7c812d6 100644 --- a/C969Project/Data/DatabaseHelper.cs +++ b/C969Project/Data/DatabaseHelper.cs @@ -1,903 +1,993 @@ -using C969Project.Data.Models; +using System; +using System.Data; // For CommandType using MySql.Data.MySqlClient; +using C969Project.Data.Models; -namespace C969Project.Data; - -public static class DatabaseHelper +namespace C969Project.Data { - - - public static void Initialize() + 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 + public static void Initialize() { - connection.Open(); + // Initialization logic if any } - catch (MySqlException ex) + + public static User? Login(string username, string password) { - Console.WriteLine(ex.Message); - } - - 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) + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try { - int id = reader.GetInt32("userId"); - return new User(id, name); + connection.Open(); + } + catch (MySqlException ex) + { + Console.WriteLine(ex.Message); + } + + 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 RetrieveCustomers() + { + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + } + catch (MySqlException e) + { + Console.WriteLine(e); + throw; + } + + List customers = new List(); + + 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; + } + + /// + /// Adds a new customer record to the database and returns the generated customerId. + /// + /// The customer object to add. + /// The ID of the newly added customer; otherwise, 0 if an error occurs. + public static int AddCustomer(Customer customer) + { + int customerId = 0; + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + + // Removed customerId from INSERT statement as it's auto-incremented + string query = + "INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy) " + + "VALUES (@customerName, @addressId, @active, @createDate, @createdBy, CURRENT_TIMESTAMP, @lastUpdateBy); " + // Use CURRENT_TIMESTAMP for lastUpdate + "SELECT LAST_INSERT_ID();"; // Get the newly generated 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); // lastUpdateBy is updated manually + + object result = command.ExecuteScalar(); + if (result != null && result != DBNull.Value) + { + customerId = Convert.ToInt32(result); + } + } + catch (MySqlException e) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + 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"; // Use CURRENT_TIMESTAMP for lastUpdate + + 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); // lastUpdateBy is updated manually + command.Parameters.AddWithValue("@customerId", customer.CustomerId); + + command.ExecuteNonQuery(); + } + catch (MySqlException e) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; } } - return null; - } - - public static List RetrieveCustomers() - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static void DeleteCustomer(int customerId) { - connection.Open(); - } - catch (MySqlException e) - { - Console.WriteLine(e); - throw; - } - - List customers = new List(); - - using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.customer", connection); - using MySqlDataReader reader = command.ExecuteReader(); - while (reader.Read()) - { - var customer = new Customer() + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try { - 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 void AddCustomer(Customer customer) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try - { - connection.Open(); - - string query = - "INSERT INTO customer (customerId, customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy) " + - "VALUES (@customerId, @customerName, @addressId, @active, @createDate, @createdBy, @lastUpdate, @lastUpdateBy)"; - - using MySqlCommand command = new MySqlCommand(query, connection); - - command.Parameters.AddWithValue("@customerId", customer.CustomerId); - 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("@lastUpdate", DateTime.UtcNow); - command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username); - - command.ExecuteNonQuery(); - } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - - 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 = @lastUpdate, 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("@lastUpdate", DateTime.UtcNow); - command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username); - command.Parameters.AddWithValue("@customerId", customer.CustomerId); - - command.ExecuteNonQuery(); - } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - - 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) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - - public static void DeleteCustomer(Customer customer) - { - DeleteCustomer(customer.CustomerId); - } - - public static Address? RetrieveAddress(int addressId) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try - { - connection.Open(); - } - catch (MySqlException e) - { - Console.WriteLine(e); - throw; - } - - 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() + 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) { - 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 List
RetrieveAllAddresses() - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try - { - connection.Open(); - } - catch (MySqlException e) - { - Console.WriteLine(e); - throw; - } - - List
addresses = new List
(); - - using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.address", connection); - using MySqlDataReader reader = command.ExecuteReader(); - while (reader.Read()) - { - var addr = new Address() + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) { - 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"), - }; - - addresses.Add(addr); + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + } + + public static void DeleteCustomer(Customer customer) + { + DeleteCustomer(customer.CustomerId); } - return addresses; - } - - public static void AddAddress(Address address) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static Address? RetrieveAddress(int addressId) { - connection.Open(); - - string query = - "INSERT INTO address (addressId, address, address2, cityId, postalCode, phone, createDate, createdBy, lastUpdate, lastUpdateBy) " + - "VALUES (@addressId, @address1, @address2, @cityId, @postalCode, @phone, @createDate, @createdBy, @lastUpdate, @lastUpdateBy)"; + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + } + catch (MySqlException e) + { + Console.WriteLine(e); + throw; + } - using MySqlCommand command = new MySqlCommand(query, connection); - - command.Parameters.AddWithValue("@addressId", address.Id); - 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("@lastUpdate", DateTime.UtcNow); - command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username); - - command.ExecuteNonQuery(); - } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - - 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 = @lastUpdate, 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("@lastUpdate", DateTime.UtcNow); - command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username); - command.Parameters.AddWithValue("@addressId", address.Id); - - command.ExecuteNonQuery(); - } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - - public static void DeleteAddress(int addressId) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try - { - connection.Open(); - string query = "DELETE FROM address WHERE addressId = @addressId"; + string query = "SELECT * FROM client_schedule.address WHERE addressId = @addressId"; using MySqlCommand command = new MySqlCommand(query, connection); command.Parameters.AddWithValue("@addressId", addressId); - command.ExecuteNonQuery(); - } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - public static void DeleteAddress(Address address) - { - DeleteAddress(address.Id); - } - - public static Appointment? RetrieveAppointment(int appointmentId) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try - { - connection.Open(); - } - catch (MySqlException e) - { - Console.WriteLine(e); - throw; - } - - string query = "SELECT * FROM client_schedule.appointment WHERE appointmentId = @appointmentId"; - using MySqlCommand command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@appointmentId", appointmentId); - - using MySqlDataReader reader = command.ExecuteReader(); - - while (reader.Read()) - { - var appt = new Appointment() + using MySqlDataReader reader = command.ExecuteReader(); + + while (reader.Read()) { - 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"), - }; + 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 appt; + return null; } - - return null; - } - public static List RetrieveAllAppointments() - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static List
RetrieveAllAddresses() { - connection.Open(); - } - catch (MySqlException e) - { - Console.WriteLine(e); - throw; - } - - List appointments = new List(); - - using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.appointment", connection); - using MySqlDataReader reader = command.ExecuteReader(); - while (reader.Read()) - { - var appt = new Appointment() + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try { - 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"), - }; + connection.Open(); + } + catch (MySqlException e) + { + Console.WriteLine(e); + throw; + } - appointments.Add(appt); + List
addresses = new List
(); + + using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.address", connection); + 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"), + }; + + addresses.Add(addr); + } + + return addresses; } - - return appointments; - } - public static void AddAppointment(Appointment appointment) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + /// + /// Adds a new address to the database and returns the generated addressId. + /// + /// The address object to add. + /// The ID of the newly added address; otherwise, 0 if an error occurs. + public static int AddAddress(Address address) { - connection.Open(); + int addressId = 0; + 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(); + // Removed addressId from INSERT statement as it's auto-incremented + 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); " + // Use CURRENT_TIMESTAMP for lastUpdate + "SELECT LAST_INSERT_ID();"; // Get the newly generated 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) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + return addressId; } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - public static void UpdateAppointment(Appointment appointment) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static void UpdateAddress(Address address) { - connection.Open(); + 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(); + string query = + "UPDATE address SET address = @address1, address2 = @address2, cityId = @cityId, postalCode = @postalCode, " + + "phone = @phone, lastUpdate = CURRENT_TIMESTAMP, lastUpdateBy = @lastUpdateBy WHERE addressId = @addressId"; // Use CURRENT_TIMESTAMP for lastUpdate + + 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) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - public static void DeleteAppointment(int appointmentId) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static void DeleteAddress(int addressId) { - connection.Open(); - string query = "DELETE FROM appointment WHERE appointmentId = @appointmentId"; + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + string query = "DELETE FROM address WHERE addressId = @addressId"; + using MySqlCommand command = new MySqlCommand(query, connection); + command.Parameters.AddWithValue("@addressId", addressId); + command.ExecuteNonQuery(); + } + catch (MySqlException e) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + } + + public static void DeleteAddress(Address address) + { + DeleteAddress(address.Id); + } + + public static Appointment? RetrieveAppointment(int appointmentId) + { + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + } + catch (MySqlException e) + { + Console.WriteLine(e); + throw; + } + + string query = "SELECT * FROM client_schedule.appointment WHERE appointmentId = @appointmentId"; using MySqlCommand command = new MySqlCommand(query, connection); command.Parameters.AddWithValue("@appointmentId", appointmentId); - command.ExecuteNonQuery(); - } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - public static void DeleteAppointment(Appointment appointment) - { - DeleteAppointment(appointment.AppointmentId); - } - - public static City? RetrieveCity(int cityId) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try - { - connection.Open(); - } - catch (MySqlException e) - { - Console.WriteLine(e); - throw; - } - - 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() + using MySqlDataReader reader = command.ExecuteReader(); + + while (reader.Read()) { - 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"), - }; + 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"), + }; + + return appt; + } - return city; + return null; } - - return null; - } - public static List RetrieveAllCities() - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static List RetrieveAllAppointments() { - connection.Open(); - } - catch (MySqlException e) - { - Console.WriteLine(e); - throw; - } - - List cities = new List(); - - using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.city", connection); - using MySqlDataReader reader = command.ExecuteReader(); - while (reader.Read()) - { - var city = new City() + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try { - 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"), - }; + connection.Open(); + } + catch (MySqlException e) + { + Console.WriteLine(e); + throw; + } - cities.Add(city); + List appointments = new List(); + + using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.appointment", connection); + 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; } - - return cities; - } - public static void AddCity(City city) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static void AddAppointment(Appointment appointment) { - connection.Open(); + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); - string query = - "INSERT INTO city (cityId, city, countryId, createDate, createdBy, lastUpdate, lastUpdateBy) " + - "VALUES (@cityId, @cityName, @countryId, @createDate, @createdBy, @lastUpdate, @lastUpdateBy)"; - - using MySqlCommand command = new MySqlCommand(query, connection); - - command.Parameters.AddWithValue("@cityId", city.CityID); - 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("@lastUpdate", DateTime.UtcNow); - command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username); - - command.ExecuteNonQuery(); + 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) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - public static void UpdateCity(City city) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static void UpdateAppointment(Appointment appointment) { - connection.Open(); + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); - string query = - "UPDATE city SET city = @cityName, countryId = @countryId, " + - "lastUpdate = @lastUpdate, lastUpdateBy = @lastUpdateBy WHERE cityId = @cityId"; - - using MySqlCommand command = new MySqlCommand(query, connection); - - command.Parameters.AddWithValue("@cityName", city.CityName); - command.Parameters.AddWithValue("@countryId", city.CountryID); - command.Parameters.AddWithValue("@lastUpdate", DateTime.UtcNow); - command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username); - command.Parameters.AddWithValue("@cityId", city.CityID); - - command.ExecuteNonQuery(); + 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) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - public static void DeleteCity(int cityId) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static void DeleteAppointment(int appointmentId) { - connection.Open(); - string query = "DELETE FROM city WHERE cityId = @cityId"; + 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) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + } + + public static void DeleteAppointment(Appointment appointment) + { + DeleteAppointment(appointment.AppointmentId); + } + + public static City? RetrieveCity(int cityId) + { + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + } + catch (MySqlException e) + { + Console.WriteLine(e); + throw; + } + + string query = "SELECT * FROM client_schedule.city WHERE cityId = @cityId"; using MySqlCommand command = new MySqlCommand(query, connection); command.Parameters.AddWithValue("@cityId", cityId); - command.ExecuteNonQuery(); - } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - public static void DeleteCity(City city) - { - DeleteCity(city.CityID); - } - - public static Country? RetrieveCountry(int countryId) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try - { - connection.Open(); - } - catch (MySqlException e) - { - Console.WriteLine(e); - throw; - } - - string query = "SELECT * FROM client_schedule.country WHERE countryId = @countryId"; - using MySqlCommand command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@countryId", countryId); - - using MySqlDataReader reader = command.ExecuteReader(); - - while (reader.Read()) - { - var country = new Country() + using MySqlDataReader reader = command.ExecuteReader(); + + while (reader.Read()) { - CountryID = reader.GetInt32("countryId"), - CountryName = reader.GetString("country"), - CreateDate = reader.GetDateTime("createDate"), - CreatedBy = reader.GetString("createdBy"), - LastUpdate = reader.GetDateTime("lastUpdate"), - LastUpdateBy = reader.GetString("lastUpdateBy"), - }; + 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 country; + return null; } - - return null; - } - public static List RetrieveAllCountries() - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static List RetrieveAllCities() { - connection.Open(); - } - catch (MySqlException e) - { - Console.WriteLine(e); - throw; - } - - List countries = new List(); - - using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.country", connection); - using MySqlDataReader reader = command.ExecuteReader(); - while (reader.Read()) - { - var country = new Country() + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try { - CountryID = reader.GetInt32("countryId"), - CountryName = reader.GetString("country"), - CreateDate = reader.GetDateTime("createDate"), - CreatedBy = reader.GetString("createdBy"), - LastUpdate = reader.GetDateTime("lastUpdate"), - LastUpdateBy = reader.GetString("lastUpdateBy"), - }; + connection.Open(); + } + catch (MySqlException e) + { + Console.WriteLine(e); + throw; + } - countries.Add(country); + List cities = new List(); + + using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.city", connection); + 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"), + }; + + cities.Add(city); + } + + return cities; } - return countries; - } + 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) + { + // TODO: Implement robust exception handling, logging, and user notification as per assignment A2b/A3b. + Console.WriteLine($"Error getting city ID: {ex.Message}"); + } + return cityId; + } + + public static int AddCity(City city) + { + int cityId = 0; + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); - public static void AddCountry(Country country) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try - { - connection.Open(); + // Removed cityId from INSERT statement as it's auto-incremented + string query = + "INSERT INTO city (city, countryId, createDate, createdBy, lastUpdate, lastUpdateBy) " + + "VALUES (@cityName, @countryId, @createDate, @createdBy, CURRENT_TIMESTAMP, @lastUpdateBy); " + // Use CURRENT_TIMESTAMP for lastUpdate + "SELECT LAST_INSERT_ID();"; // Get the newly generated 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) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + return cityId; + } - string query = - "INSERT INTO country (countryId, country, createDate, createdBy, lastUpdate, lastUpdateBy) " + - "VALUES (@countryId, @countryName, @createDate, @createdBy, @lastUpdate, @lastUpdateBy)"; - - using MySqlCommand command = new MySqlCommand(query, connection); - - command.Parameters.AddWithValue("@countryId", country.CountryID); - command.Parameters.AddWithValue("@countryName", country.CountryName); - 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) + public static void UpdateCity(City city) { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); - public static void UpdateCountry(Country country) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try - { - connection.Open(); + string query = + "UPDATE city SET city = @cityName, countryId = @countryId, " + + "lastUpdate = CURRENT_TIMESTAMP, lastUpdateBy = @lastUpdateBy WHERE cityId = @cityId"; // Use CURRENT_TIMESTAMP for lastUpdate + + using MySqlCommand command = new MySqlCommand(query, connection); + + command.Parameters.AddWithValue("@cityName", city.CityName); + command.Parameters.AddWithValue("@countryId", city.CountryID); + command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username); + command.Parameters.AddWithValue("@cityId", city.CityID); + + command.ExecuteNonQuery(); + } + catch (MySqlException e) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + } - string query = - "UPDATE country SET country = @countryName, " + - "lastUpdate = @lastUpdate, lastUpdateBy = @lastUpdateBy WHERE countryId = @countryId"; - - using MySqlCommand command = new MySqlCommand(query, connection); - - command.Parameters.AddWithValue("@countryName", country.CountryName); - command.Parameters.AddWithValue("@lastUpdate", DateTime.UtcNow); - command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username); - command.Parameters.AddWithValue("@countryId", country.CountryID); - - command.ExecuteNonQuery(); - } - catch (MySqlException e) + public static void DeleteCity(int cityId) { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + string query = "DELETE FROM city WHERE cityId = @cityId"; + using MySqlCommand command = new MySqlCommand(query, connection); + command.Parameters.AddWithValue("@cityId", cityId); + command.ExecuteNonQuery(); + } + catch (MySqlException e) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - public static void DeleteCountry(int countryId) - { - using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); - try + public static void DeleteCity(City city) { - connection.Open(); - string query = "DELETE FROM country WHERE countryId = @countryId"; + DeleteCity(city.CityID); + } + + public static Country? RetrieveCountry(int countryId) + { + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + } + catch (MySqlException e) + { + Console.WriteLine(e); + throw; + } + + string query = "SELECT * FROM client_schedule.country WHERE countryId = @countryId"; using MySqlCommand command = new MySqlCommand(query, connection); command.Parameters.AddWithValue("@countryId", countryId); - command.ExecuteNonQuery(); - } - catch (MySqlException e) - { - Console.WriteLine($"MySQL Error: {e.Message}"); - throw; - } - catch (Exception ex) - { - Console.WriteLine($"General Error: {ex.Message}"); - throw; - } - } - public static void DeleteCountry(Country country) - { - DeleteCountry(country.CountryID); + using MySqlDataReader reader = command.ExecuteReader(); + + while (reader.Read()) + { + var country = new Country() + { + CountryID = reader.GetInt32("countryId"), + CountryName = reader.GetString("country"), + CreateDate = reader.GetDateTime("createDate"), + CreatedBy = reader.GetString("createdBy"), + LastUpdate = reader.GetDateTime("lastUpdate"), + LastUpdateBy = reader.GetString("lastUpdateBy"), + }; + + return country; + } + + return null; + } + + public static List RetrieveAllCountries() + { + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + } + catch (MySqlException e) + { + Console.WriteLine(e); + throw; + } + + List countries = new List(); + + using MySqlCommand command = new MySqlCommand("SELECT * FROM client_schedule.country", connection); + using MySqlDataReader reader = command.ExecuteReader(); + while (reader.Read()) + { + var country = new Country() + { + CountryID = reader.GetInt32("countryId"), + CountryName = reader.GetString("country"), + CreateDate = reader.GetDateTime("createDate"), + CreatedBy = reader.GetString("createdBy"), + LastUpdate = reader.GetDateTime("lastUpdate"), + LastUpdateBy = reader.GetString("lastUpdateBy"), + }; + + countries.Add(country); + } + + return 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) + { + // TODO: Implement robust exception handling, logging, and user notification as per assignment A2b/A3b. + Console.WriteLine($"Error getting country ID: {ex.Message}"); + } + return countryId; + } + + public static int AddCountry(Country country) + { + int countryId = 0; + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + + // Removed countryId from INSERT statement as it's auto-incremented + string query = + "INSERT INTO country (country, createDate, createdBy, lastUpdate, lastUpdateBy) " + + "VALUES (@countryName, @createDate, @createdBy, CURRENT_TIMESTAMP, @lastUpdateBy); " + // Use CURRENT_TIMESTAMP for lastUpdate + "SELECT LAST_INSERT_ID();"; // Get the newly generated 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) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + return countryId; + } + + public static void UpdateCountry(Country country) + { + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + + string query = + "UPDATE country SET country = @countryName, " + + "lastUpdate = CURRENT_TIMESTAMP, lastUpdateBy = @lastUpdateBy WHERE countryId = @countryId"; // Use CURRENT_TIMESTAMP for lastUpdate + + using MySqlCommand command = new MySqlCommand(query, connection); + + command.Parameters.AddWithValue("@countryName", country.CountryName); + command.Parameters.AddWithValue("@lastUpdateBy", AppState.CurrentUser.Username); + command.Parameters.AddWithValue("@countryId", country.CountryID); + + command.ExecuteNonQuery(); + } + catch (MySqlException e) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + } + + public static void DeleteCountry(int countryId) + { + using MySqlConnection connection = new MySqlConnection(AppSettings.GetSetting("ConnectionStrings", "DefaultConnection")); + try + { + connection.Open(); + string query = "DELETE FROM country WHERE countryId = @countryId"; + using MySqlCommand command = new MySqlCommand(query, connection); + command.Parameters.AddWithValue("@countryId", countryId); + command.ExecuteNonQuery(); + } + catch (MySqlException e) + { + Console.WriteLine($"MySQL Error: {e.Message}"); + throw; + } + catch (Exception ex) + { + Console.WriteLine($"General Error: {ex.Message}"); + throw; + } + } + + public static void DeleteCountry(Country country) + { + DeleteCountry(country.CountryID); + } } } \ No newline at end of file diff --git a/C969Project/RecordsForm.cs b/C969Project/RecordsForm.cs index 3a37b4e..788a7f0 100644 --- a/C969Project/RecordsForm.cs +++ b/C969Project/RecordsForm.cs @@ -16,12 +16,14 @@ public partial class RecordsForm : Form AddButton.Click += (sender, args) => { _form.InitAdd(); + _form.Closed += (o, args2) => { UpdateCustomersList(); }; }; ModifyButton.Click += (sender, args) => { var selectedCustomer = _customers[CustomersDataGrid.CurrentCell.RowIndex]; _form.InitUpdate(selectedCustomer); + _form.Closed += (o, args2) => { UpdateCustomersList(); }; }; DeleteButton.Click += (sender, args) =>