From 48be020dc4186ecf2d3d262c4f741e37750d5aa4 Mon Sep 17 00:00:00 2001 From: Frozd Date: Mon, 2 Mar 2026 14:23:15 +0100 Subject: [PATCH 1/5] feat: GUID --- CarManagerV3/Car.cs | 80 +++++++++++++++++++++++--------- CarManagerV3/CarDetailsForm.cs | 6 +-- CarManagerV3/CarManagerV3.csproj | 1 + CarManagerV3/Class1.cs | 12 +++++ CarManagerV3/MainForm.cs | 38 ++++++++++----- CarManagerV3/SafeManager.cs | 40 ++++++++++++++-- CarManagerV3/StateManager.cs | 25 ++++++++-- 7 files changed, 158 insertions(+), 44 deletions(-) create mode 100644 CarManagerV3/Class1.cs diff --git a/CarManagerV3/Car.cs b/CarManagerV3/Car.cs index 5f67a01..8b7d0a4 100644 --- a/CarManagerV3/Car.cs +++ b/CarManagerV3/Car.cs @@ -7,7 +7,7 @@ namespace CarManagerV3 /// public class Car { - private int id; + private string id; private string make; private string model; private int year; @@ -16,14 +16,11 @@ namespace CarManagerV3 private decimal price; private int order; - public int Id { get => id; - set { - if (value < 0) throw new ArgumentException("Id cannot be negative."); - id = value; - } - } + public string Id { get => id; } - public string Make { get => make; + public string Make + { + get => make; set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Make cannot be empty."); @@ -31,7 +28,9 @@ namespace CarManagerV3 } } - public string Model { get => model; + public string Model + { + get => model; set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Model cannot be empty."); @@ -39,7 +38,9 @@ namespace CarManagerV3 } } - public int Year { get => year; + public int Year + { + get => year; set { if (value < 1886 || value > DateTime.Now.Year + 1) throw new ArgumentException("Year must be between 1886 and next year."); @@ -47,7 +48,9 @@ namespace CarManagerV3 } } - public string Color { get => color; + public string Color + { + get => color; set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Color cannot be empty."); @@ -55,7 +58,9 @@ namespace CarManagerV3 } } - public int Mileage { get => mileage; + public int Mileage + { + get => mileage; set { if (value < 0) throw new ArgumentException("Mileage cannot be negative."); @@ -63,7 +68,9 @@ namespace CarManagerV3 } } - public decimal Price { get => price; + public decimal Price + { + get => price; set { if (value < 0) throw new ArgumentException("Price cannot be negative."); @@ -102,10 +109,21 @@ namespace CarManagerV3 /// The current mileage on the car. /// The selling-price of the car. /// The order. - public Car(int id, string make, string model, int year, string color, int mileage, decimal price, int order = 0) + public Car(string id, string make, string model, int year, string color, int mileage, decimal price, int order = 0) { + // is ID just a number? Then it is legacy and needs a new ID string. + int numericId = 0; + if ((string.IsNullOrWhiteSpace(id) || int.TryParse(id, out numericId)) && id != "0") + { + id = Guid.NewGuid().ToString(); + if (numericId > 0) + { + order = numericId + order; + } + + } // Sets the properties using the setters to ensure validation is applied. - this.Id = id; + this.id = id; this.Make = make; this.Model = model; this.Year = year; @@ -137,7 +155,7 @@ namespace CarManagerV3 /// public string ToCsvString() { - return $"{this.Id};{this.Make};{this.Model};{this.Year};{this.Color};{this.Mileage};{this.Price}"; + return $"{this.Id};{this.Make};{this.Model};{this.Year};{this.Color};{this.Mileage};{this.Price};{this.Order}"; } //TODO: Add error handling for malformed CSV strings and detection for missing fields. @@ -156,10 +174,23 @@ namespace CarManagerV3 try { string[] parts = csv.Split(';'); - Car temp = new Car(int.Parse(parts[0]), parts[1], parts[2], int.Parse(parts[3]), parts[4], int.Parse(parts[5]), decimal.Parse(parts[6])); - if (temp.Year < 1886 || temp.Year > DateTime.Now.Year + 1) throw new Exception($"Invalid year: {temp.Year}"); - if (temp.Mileage < 0) throw new Exception($"Mileage cannot be negative: {temp.Mileage}"); - if (temp.Price < 0) throw new Exception($"Price cannot be negative: {temp.Price}"); + // is part 7 a valid int? if not set it to 0 and log a warning. + if (parts.Length == 7) + { + Console.Error.WriteLine($"Warning: CSV string has only 7 fields, expected 8. Setting Order to 0. CSV: {csv}"); + if (!StateManager.askForMigration()) + { + throw new Exception("User declined migration. Cannot parse CSV string with missing Order field."); + } + Array.Resize(ref parts, 8); + parts[7] = "0"; + } + else if (parts.Length != 8) + { + throw new FormatException($"CSV string has {parts.Length} fields, expected 8. CSV: {csv}"); + } + + Car temp = new Car(parts[0], parts[1], parts[2], int.Parse(parts[3]), parts[4], int.Parse(parts[5]), decimal.Parse(parts[6]), int.Parse(parts[7])); return temp; } catch (Exception ex) @@ -187,7 +218,14 @@ namespace CarManagerV3 /// An identical but seperate public Car Clone() { - return new Car(this.Id, this.Make, this.Model, this.Year, this.Color, this.Mileage, this.Price); + return new Car(this.Id, this.Make, this.Model, this.Year, this.Color, this.Mileage, this.Price, this.Order); + } + + + public static bool isLegacyCsvString(string csv) + { + string[] parts = csv.Split(';'); + return parts.Length == 7; // Legacy format has 7 fields, new format has 8 fields (with Order). } } } diff --git a/CarManagerV3/CarDetailsForm.cs b/CarManagerV3/CarDetailsForm.cs index bbd3e0d..43215c6 100644 --- a/CarManagerV3/CarDetailsForm.cs +++ b/CarManagerV3/CarDetailsForm.cs @@ -21,7 +21,7 @@ namespace CarManagerV3 nudPrice.Value = car.Price; tbxAge.Text = car.AgeString; pbxCarImage.Image = ImageManager.GetImage(car); - if (car.Id == 0) + if (car.Id == "0") { lblID.Text = "New Car"; } @@ -125,7 +125,7 @@ namespace CarManagerV3 msgbox.Show(); await Task.Run(() => { - if(car.Id == 0) { + if(car.Id == "0") { car = StateManager.CreateCar(car.Make, car.Model, car.Year, car.Color, car.Mileage, car.Price); } else { @@ -145,7 +145,7 @@ namespace CarManagerV3 private void btnDelete_Click(object sender, EventArgs e) { - if(car.Id == 0) + if(car.Id == "0") { //just close form if car is not saved yet this.Close(); diff --git a/CarManagerV3/CarManagerV3.csproj b/CarManagerV3/CarManagerV3.csproj index 7e0a20f..2b42b76 100644 --- a/CarManagerV3/CarManagerV3.csproj +++ b/CarManagerV3/CarManagerV3.csproj @@ -68,6 +68,7 @@ CarCard.cs + Form diff --git a/CarManagerV3/Class1.cs b/CarManagerV3/Class1.cs new file mode 100644 index 0000000..ba23fd9 --- /dev/null +++ b/CarManagerV3/Class1.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarManagerV3 +{ + internal class LegacyException : Exception + { + } +} diff --git a/CarManagerV3/MainForm.cs b/CarManagerV3/MainForm.cs index f22ba3f..aed2273 100644 --- a/CarManagerV3/MainForm.cs +++ b/CarManagerV3/MainForm.cs @@ -25,13 +25,26 @@ namespace CarManagerV3 SafeManager.InitializeFile(filepath); StateManager.setFilePath(filepath); - List _cars = SafeManager.ReadCars(filepath); - - refreshCars(_cars); - refreshRecents(); + try + { + List _cars = SafeManager.ReadCars(filepath); + cars = _cars; + refreshCars(_cars, false); + } + catch (LegacyException) + { + Console.Error.WriteLine("Legacy file format detected. Prompting user to select a new file."); + showOpenFileDialog(); + } } + public void showOpenFileDialog() + { + openToolStripMenuItem.PerformClick(); + } + + /// /// Refreshes the cars displayed in the flow layout panel. /// @@ -135,7 +148,7 @@ namespace CarManagerV3 private void btnNewCar_Click(object sender, EventArgs e) { - Car foocar = new Car(0, "New", "Car", 2020, "White", 0, 20000); + Car foocar = new Car("0", "New", "Car", 2020, "White", 0, 20000); CarDetailsForm detailsForm = new CarDetailsForm(foocar); detailsForm.FormClosed += (s2, e2) => { @@ -226,6 +239,10 @@ namespace CarManagerV3 SafeManager.AddRecentPath(filepath); refreshRecents(); } + catch (LegacyException) + { + showOpenFileDialog(); + } catch (Exception ex) { MessageBox.Show("Error loading file: " + ex.Message); @@ -294,13 +311,6 @@ namespace CarManagerV3 // merge cars foreach (Car car in importedCars) { - // check if car with same ID exists - if (cars.Any(c => c.Id == car.Id)) - { - // assign new ID - int newId = cars.Count > 0 ? cars.Max(c => c.Id) + 1 : 1; - car.Id = newId; - } cars.Add(car); } DialogResult mergeAsNewFileResult = MessageBox.Show("Do you want to save the merged cars as a new file?", "Save As New File", MessageBoxButtons.YesNo, MessageBoxIcon.Question); @@ -330,6 +340,10 @@ namespace CarManagerV3 refreshCars(cars); MessageBox.Show("File imported successfully.", "Import File", MessageBoxButtons.OK, MessageBoxIcon.Information); } + catch (LegacyException) + { + MessageBox.Show("The file you are trying to import is in a legacy format that is no longer supported. Please convert the file to the new format and try again.", "Import Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + } catch (Exception ex) { MessageBox.Show("Error importing file: " + ex.Message); diff --git a/CarManagerV3/SafeManager.cs b/CarManagerV3/SafeManager.cs index 7751184..47aefad 100644 --- a/CarManagerV3/SafeManager.cs +++ b/CarManagerV3/SafeManager.cs @@ -17,6 +17,7 @@ namespace CarManagerV3 /// private static readonly string recentPathsFile = "recent_paths.txt"; + /// /// Initializes a file at a specified path if it does not already exist. /// @@ -52,6 +53,7 @@ namespace CarManagerV3 { List cars = new List(); List failedLines = new List(); + bool isLegacy = false; try { using (StreamReader reader = new StreamReader(@path)) @@ -61,17 +63,35 @@ namespace CarManagerV3 { // Process the line if (line == "") continue; + if (Car.isLegacyCsvString(line)) + { + if (!StateManager.askForMigration()) + { + MessageBox.Show("The file you are trying to open is in an old format that is no longer supported. Please select a different file.", "Unsupported Format", MessageBoxButtons.OK, MessageBoxIcon.Error); + throw new LegacyException(); + //Environment.Exit(0); + } + else + { + isLegacy = true; + } + } Car tmp = Car.FromCsvString(line); if (tmp == null) { failedLines.Add(line); continue; - } + } cars.Add(tmp); } reader.Close(); } - } catch (Exception ex) + } + catch (LegacyException ex) + { + throw ex; + } + catch (Exception ex) { Console.Error.WriteLine($"Error reading cars from file: {ex.Message}"); } @@ -84,6 +104,11 @@ namespace CarManagerV3 } MessageBox.Show($"Warning: {failedLines.Count} lines in the file could not be parsed and were skipped. Check the console for details.", "Parsing Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } + cars = cars.OrderBy(c => c.Order).ToList(); + if(isLegacy) + { + SafeManager.SaveCars(path, cars); + } return cars; } @@ -104,7 +129,8 @@ namespace CarManagerV3 } writer.Close(); } - } catch (Exception ex) + } + catch (Exception ex) { Console.Error.WriteLine($"Error saving cars to file: {ex.Message}"); MessageBox.Show($"Error saving cars to file: {ex.Message}", "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -149,7 +175,8 @@ namespace CarManagerV3 } writer.Close(); } - } catch (Exception ex) + } + catch (Exception ex) { Console.Error.WriteLine($"Error managing recent paths: {ex.Message}"); } @@ -178,11 +205,14 @@ namespace CarManagerV3 reader.Close(); } } - } catch (Exception ex) + } + catch (Exception ex) { Console.Error.WriteLine($"Error reading recent paths: {ex.Message}"); } return paths; } + + } } diff --git a/CarManagerV3/StateManager.cs b/CarManagerV3/StateManager.cs index 93a8258..e635dd6 100644 --- a/CarManagerV3/StateManager.cs +++ b/CarManagerV3/StateManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Windows.Forms; namespace CarManagerV3 { @@ -17,6 +18,10 @@ namespace CarManagerV3 // TODO: If no recent file paths are found, prompt user to select a file path instead of using a hardcoded default in the program folder. static string filePath = "cars.csv"; + static bool hasConfirmedMigration = false; + + + /// /// Gets a car by its identifier. /// @@ -24,7 +29,7 @@ namespace CarManagerV3 /// /// A object if found; otherwise, null. /// - public static Car GetCarById(int id) + public static Car GetCarById(string id) { cars = SafeManager.ReadCars(filePath); return cars.FirstOrDefault(c => c.Id == id); @@ -96,8 +101,8 @@ namespace CarManagerV3 public static Car CreateCar(string make, string model, int year, string color, int mileage, decimal price) { cars = SafeManager.ReadCars(filePath); - int newId = cars.Count > 0 ? cars.Max(c => c.Id) + 1 : 1; - Car newCar = new Car(newId, make, model, year, color, mileage, price); + int newOrder = cars.Count > 0 ? cars.Max(c => c.Order) + 1 : 1; + Car newCar = new Car("", make, model, year, color, mileage, price, newOrder); AddCar(newCar); return newCar; } @@ -109,7 +114,21 @@ namespace CarManagerV3 /// The path. public static void setFilePath(string path) { + // Reset migration confirmation when changing file path, as the new file may also require migration. + hasConfirmedMigration = false; filePath = path; } + + public static bool askForMigration() + { + if (hasConfirmedMigration) + { + return true; + } + DialogResult result = MessageBox.Show("The file you are trying to open is in an older format. Do you want to attempt to migrate it to the new format? If you choose not to migrate, the file will not be opened.", "Migration Needed", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); + hasConfirmedMigration = result == DialogResult.Yes; + return hasConfirmedMigration; + } + } } From 272ed999d8863c78be1bf53fd7496b4cd81a43ad Mon Sep 17 00:00:00 2001 From: Frozd Date: Mon, 2 Mar 2026 15:33:56 +0100 Subject: [PATCH 2/5] feat: reordering --- CarManagerV3/Car.cs | 2 +- CarManagerV3/CarCard.Designer.cs | 4 +-- CarManagerV3/CarCard.cs | 21 +++++++++---- CarManagerV3/CarCard.resx | 4 +-- CarManagerV3/CarManagerV3.csproj | 5 ++- CarManagerV3/Class1.cs | 12 ------- CarManagerV3/LegacyException.cs | 16 ++++++++++ CarManagerV3/MainForm.cs | 54 +++++++++++++++++++++++++++----- CarManagerV3/SafeManager.cs | 24 ++++++++++++-- CarManagerV3/StateManager.cs | 11 +++++++ 10 files changed, 119 insertions(+), 34 deletions(-) delete mode 100644 CarManagerV3/Class1.cs create mode 100644 CarManagerV3/LegacyException.cs diff --git a/CarManagerV3/Car.cs b/CarManagerV3/Car.cs index 8b7d0a4..431da59 100644 --- a/CarManagerV3/Car.cs +++ b/CarManagerV3/Car.cs @@ -209,7 +209,7 @@ namespace CarManagerV3 /// public bool IsChanged(Car other) { - return this.Make != other.Make || this.Model != other.Model || this.Year != other.Year || this.Color != other.Color || this.Mileage != other.Mileage || this.Price != other.Price || this.Color != other.Color; + return this.Make != other.Make || this.Model != other.Model || this.Year != other.Year || this.Color != other.Color || this.Mileage != other.Mileage || this.Price != other.Price || this.Color != other.Color || this.Order != other.Order; } /// diff --git a/CarManagerV3/CarCard.Designer.cs b/CarManagerV3/CarCard.Designer.cs index 9a0184a..b7a2443 100644 --- a/CarManagerV3/CarCard.Designer.cs +++ b/CarManagerV3/CarCard.Designer.cs @@ -59,7 +59,7 @@ // lblCarDetails // this.lblCarDetails.AutoSize = true; - this.lblCarDetails.Location = new System.Drawing.Point(3, 184); + this.lblCarDetails.Location = new System.Drawing.Point(3, 174); this.lblCarDetails.Name = "lblCarDetails"; this.lblCarDetails.Size = new System.Drawing.Size(101, 16); this.lblCarDetails.TabIndex = 5; @@ -72,7 +72,7 @@ this.lblCarName.Font = new System.Drawing.Font("Arial", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblCarName.Location = new System.Drawing.Point(3, 130); this.lblCarName.Name = "lblCarName"; - this.lblCarName.Size = new System.Drawing.Size(204, 54); + this.lblCarName.Size = new System.Drawing.Size(204, 44); this.lblCarName.TabIndex = 4; this.lblCarName.Text = "Skoda Fabia fdsdfsdfsdfsdf"; this.lblCarName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; diff --git a/CarManagerV3/CarCard.cs b/CarManagerV3/CarCard.cs index 1c34a6f..ece30c1 100644 --- a/CarManagerV3/CarCard.cs +++ b/CarManagerV3/CarCard.cs @@ -38,12 +38,14 @@ namespace CarManagerV3 foreach (Control ctrl in this.Controls) { - ctrl.Click += ForwardClick; - foreach (Control inner in ctrl.Controls) // In case you have nested controls - inner.Click += ForwardClick; + ctrl.MouseClick += ForwardClick; + foreach (Control inner in ctrl.Controls) + { + inner.MouseClick += ForwardClick; + } } - this.Click += (s, e) => this.OnCardClicked(); + this.MouseClick += (s, e) => this.OnCardClicked(s, e); } public async void LoadImage() @@ -59,15 +61,22 @@ namespace CarManagerV3 }); } - private void ForwardClick(object sender, EventArgs e) + private void ForwardClick(object sender, MouseEventArgs e) { // Raise your CardClicked event no matter what got clicked + if (e.Button == MouseButtons.Right) return; + + Console.WriteLine($"Forwarding click from {sender.GetType().Name}"); CardClicked?.Invoke(this, EventArgs.Empty); } public event EventHandler CardClicked; - private void OnCardClicked() + private void OnCardClicked(object sender, MouseEventArgs e) { + Console.WriteLine($"Card clicked at {e.Location} with button {e.Button}"); + if (e.Button == MouseButtons.Right) return; + Console.WriteLine($"Card clicked: {this.CarName}"); + if (this.CardClicked != null) { this.CardClicked(this, EventArgs.Empty); diff --git a/CarManagerV3/CarCard.resx b/CarManagerV3/CarCard.resx index ca00d24..0850e49 100644 --- a/CarManagerV3/CarCard.resx +++ b/CarManagerV3/CarCard.resx @@ -121,7 +121,7 @@ iVBORw0KGgoAAAANSUhEUgAABLAAAALuCAYAAAC+de9yAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAL - EgAACxIB0t1+/AAA/7JJREFUeF7s/fuXZ8dZ349K5gs2dggQCJeYXAADx+IWooRLwsUc8Jc44QBfgpwE + EQAACxEBf2RfkQAA/7JJREFUeF7s/fuXZ8dZ349K5gs2dggQCJeYXAADx+IWooRLwsUc8Jc44QBfgpwE MNiAbQIYI3yRrZHUv50VlhewCHG8tIyQLVmyaY/m0jM9PT09Mz33W3dPT09Pz4zGwsn5S3RWXZ6n3s+7 an96ZBvb2O/3Ws/au+61a9duTb30VH3uuUeSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmS JEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmS @@ -5505,7 +5505,7 @@ iVBORw0KGgoAAAANSUhEUgAABLAAAALuCAYAAAC+de9yAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAL - EgAACxIB0t1+/AAA/7JJREFUeF7s/fuXZ8dZ349K5gs2dggQCJeYXAADx+IWooRLwsUc8Jc44QBfgpwE + EQAACxEBf2RfkQAA/7JJREFUeF7s/fuXZ8dZ349K5gs2dggQCJeYXAADx+IWooRLwsUc8Jc44QBfgpwE MNiAbQIYI3yRrZHUv50VlhewCHG8tIyQLVmyaY/m0jM9PT09Mz33W3dPT09Pz4zGwsn5S3RWXZ6n3s+7 an96ZBvb2O/3Ws/au+61a9duTb30VH3uuUeSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmS JEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmS diff --git a/CarManagerV3/CarManagerV3.csproj b/CarManagerV3/CarManagerV3.csproj index 2b42b76..0dcc141 100644 --- a/CarManagerV3/CarManagerV3.csproj +++ b/CarManagerV3/CarManagerV3.csproj @@ -68,7 +68,7 @@ CarCard.cs - + Form @@ -139,5 +139,8 @@ false + + + \ No newline at end of file diff --git a/CarManagerV3/Class1.cs b/CarManagerV3/Class1.cs deleted file mode 100644 index ba23fd9..0000000 --- a/CarManagerV3/Class1.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CarManagerV3 -{ - internal class LegacyException : Exception - { - } -} diff --git a/CarManagerV3/LegacyException.cs b/CarManagerV3/LegacyException.cs new file mode 100644 index 0000000..e9fd65c --- /dev/null +++ b/CarManagerV3/LegacyException.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarManagerV3 +{ + /// + /// LegacyException is a custom exception class used to indicate that a file is in a legacy format that cannot be read by the current version of the application. It is thrown when the SafeManager encounters a file format that it does not recognize, allowing the application to handle this specific case separately from other types of exceptions. + /// + /// + internal class LegacyException : Exception + { + } +} diff --git a/CarManagerV3/MainForm.cs b/CarManagerV3/MainForm.cs index aed2273..e5dd190 100644 --- a/CarManagerV3/MainForm.cs +++ b/CarManagerV3/MainForm.cs @@ -37,6 +37,8 @@ namespace CarManagerV3 showOpenFileDialog(); } + refreshRecents(); + } public void showOpenFileDialog() @@ -56,7 +58,7 @@ namespace CarManagerV3 this.Text = "Car Manager - " + System.IO.Path.GetFileName(filepath); // Sort by Car.Order. If equal, sort by ID - _cars = _cars.Count > 0 ? _cars.OrderBy(c => c.Order).ThenBy(c => c.Id).ToList() : _cars; + _cars = _cars.Count > 0 ? _cars.OrderBy(c => c.Order).ToList() : _cars; if (updateGlobal) { @@ -79,7 +81,7 @@ namespace CarManagerV3 continue; } // compare details - Console.WriteLine($"[L] Checking car: {car.Id} | Car Color: {car.Color} | Ex Color: {existingCar.Color}"); + // Console.WriteLine($"[L] Checking car: {car.Id} | Car Color: {car.Color} | Ex Color: {existingCar.Color}"); if (existingCar.IsChanged(car)) { Console.WriteLine($"[L] Updating car: {car.Id}"); @@ -90,14 +92,14 @@ namespace CarManagerV3 else { // no changes - Console.WriteLine($"[L] No changes for car: {car.Id}"); + // Console.WriteLine($"[L] No changes for car: {car.Id}"); flpCars.Controls.SetChildIndex(existing, _cars.IndexOf(car)); continue; } } card.CarName = $"{car.Make} {car.Model}"; - card.CarDetails = $"{car.Year}, {car.Mileage} km, ${car.Price}"; + card.CarDetails = $"({car.Order}) {car.Year}, {car.Mileage} km, ${car.Price}"; card.Car = car.Clone(); card.LoadImage(); // clear existing event handlers to prevent multiple subscriptions @@ -125,6 +127,42 @@ namespace CarManagerV3 detailsForm.ShowDialog(); }; + ContextMenu cm = new ContextMenu(); + cm.MenuItems.Add(new MenuItem("Move Up", (s, e) => + { + int order = car.Order; + // find car with order just less than this one + Car other = cars.Where(c => c.Order < order).OrderByDescending(c => c.Order).FirstOrDefault(); + if (other != null) + { + Console.WriteLine($"Swapping order of {car.ToString()} ({car.Order}) and {other.ToString()} ({other.Order})"); + int temp = car.Order; + car.Order = other.Order; + other.Order = temp; + SafeManager.SaveCars(filepath, cars); + refreshCars(cars); + } + })); + + cm.MenuItems.Add(new MenuItem("Move Down", (s, e) => + { + + int order = car.Order; + // find car with order just greater than this one + Car other = cars.Where(c => c.Order > order).OrderBy(c => c.Order).FirstOrDefault(); + if (other != null) + { + Console.WriteLine($"Swapping order of {car.ToString()} ({car.Order}) and {other.ToString()} ({other.Order})"); + int temp = car.Order; + car.Order = other.Order; + other.Order = temp; + SafeManager.SaveCars(filepath, cars); + refreshCars(cars); + } + })); + + card.ContextMenu = cm; + if (isNew) { flpCars.Controls.Add(card); @@ -217,7 +255,7 @@ namespace CarManagerV3 dlgOpen.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*"; dlgOpen.Title = "Open Car Data File"; // Default to users documents - dlgOpen.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + dlgOpen.InitialDirectory = SafeManager.getRecentFolder(); DialogResult result = dlgOpen.ShowDialog(); if (result == DialogResult.OK) @@ -263,7 +301,7 @@ namespace CarManagerV3 dlgSave.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*"; dlgSave.Title = "Save Car Data File As"; // Default to users documents - dlgSave.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + dlgSave.InitialDirectory = SafeManager.getRecentFolder(); DialogResult result = dlgSave.ShowDialog(); if (result == DialogResult.OK) @@ -296,7 +334,7 @@ namespace CarManagerV3 dlgOpen.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*"; dlgOpen.Title = "Import Car Data File"; // Default to users documents - dlgOpen.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + dlgOpen.InitialDirectory = SafeManager.getRecentFolder(); DialogResult dlgResult = dlgOpen.ShowDialog(); if (dlgResult == DialogResult.OK) { @@ -320,7 +358,7 @@ namespace CarManagerV3 dlgSave.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*"; dlgSave.Title = "Save Merged Car Data File As"; // Default to users documents - dlgSave.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + dlgSave.InitialDirectory = SafeManager.getRecentFolder(); DialogResult saveResult = dlgSave.ShowDialog(); if (saveResult == DialogResult.OK) { diff --git a/CarManagerV3/SafeManager.cs b/CarManagerV3/SafeManager.cs index 47aefad..9f94e73 100644 --- a/CarManagerV3/SafeManager.cs +++ b/CarManagerV3/SafeManager.cs @@ -104,8 +104,9 @@ namespace CarManagerV3 } MessageBox.Show($"Warning: {failedLines.Count} lines in the file could not be parsed and were skipped. Check the console for details.", "Parsing Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } + cars = StateManager.normalizeOrders(cars); cars = cars.OrderBy(c => c.Order).ToList(); - if(isLegacy) + if (isLegacy) { SafeManager.SaveCars(path, cars); } @@ -213,6 +214,25 @@ namespace CarManagerV3 return paths; } - + /// + /// Gets the folder of the most recently opened file, or the users documents folder if no recent files. + /// + /// + public static string getRecentFolder() + { + List recentPaths = GetRecentPaths(); + if (recentPaths.Count > 0) + { + string recentFile = recentPaths[0]; + if (File.Exists(recentFile)) + { + return Path.GetDirectoryName(recentFile); + } + } + return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + } + + + } } diff --git a/CarManagerV3/StateManager.cs b/CarManagerV3/StateManager.cs index e635dd6..23ecba5 100644 --- a/CarManagerV3/StateManager.cs +++ b/CarManagerV3/StateManager.cs @@ -119,6 +119,17 @@ namespace CarManagerV3 filePath = path; } + public static List normalizeOrders(List cars) + { + // Normalize the Order field of all cars to be sequential starting from 1, while keeping the relative order the same. + var orderedCars = cars.OrderBy(c => c.Order).ToList(); + for (int i = 0; i < orderedCars.Count; i++) + { + orderedCars[i].Order = i + 1; + } + return orderedCars; + } + public static bool askForMigration() { if (hasConfirmedMigration) From a6112bec44ca73715916bbfd6839ebca957eb210 Mon Sep 17 00:00:00 2001 From: Frozd Date: Mon, 2 Mar 2026 16:01:12 +0100 Subject: [PATCH 3/5] chore: folders --- CarManagerV3/CarManagerV3.csproj | 39 +++++++++---------- CarManagerV3/{ => Classes}/Car.cs | 0 .../{ => Exceptions}/LegacyException.cs | 0 .../{ => Forms}/CarDetailsForm.Designer.cs | 0 CarManagerV3/{ => Forms}/CarDetailsForm.cs | 0 CarManagerV3/{ => Forms}/CarDetailsForm.resx | 0 .../Components}/CarCard.Designer.cs | 0 .../{ => Forms/Components}/CarCard.cs | 0 .../{ => Forms/Components}/CarCard.resx | 0 CarManagerV3/{ => Forms}/MainForm.Designer.cs | 20 +++++----- CarManagerV3/{ => Forms}/MainForm.cs | 0 CarManagerV3/{ => Forms}/MainForm.resx | 0 .../{ => Forms/Util}/PleaseWait.Designer.cs | 0 CarManagerV3/{ => Forms/Util}/PleaseWait.cs | 0 CarManagerV3/{ => Forms/Util}/PleaseWait.resx | 0 CarManagerV3/{ => Manager}/ImageManager.cs | 0 CarManagerV3/{ => Manager}/SafeManager.cs | 0 CarManagerV3/{ => Manager}/StateManager.cs | 0 18 files changed, 29 insertions(+), 30 deletions(-) rename CarManagerV3/{ => Classes}/Car.cs (100%) rename CarManagerV3/{ => Exceptions}/LegacyException.cs (100%) rename CarManagerV3/{ => Forms}/CarDetailsForm.Designer.cs (100%) rename CarManagerV3/{ => Forms}/CarDetailsForm.cs (100%) rename CarManagerV3/{ => Forms}/CarDetailsForm.resx (100%) rename CarManagerV3/{ => Forms/Components}/CarCard.Designer.cs (100%) rename CarManagerV3/{ => Forms/Components}/CarCard.cs (100%) rename CarManagerV3/{ => Forms/Components}/CarCard.resx (100%) rename CarManagerV3/{ => Forms}/MainForm.Designer.cs (98%) rename CarManagerV3/{ => Forms}/MainForm.cs (100%) rename CarManagerV3/{ => Forms}/MainForm.resx (100%) rename CarManagerV3/{ => Forms/Util}/PleaseWait.Designer.cs (100%) rename CarManagerV3/{ => Forms/Util}/PleaseWait.cs (100%) rename CarManagerV3/{ => Forms/Util}/PleaseWait.resx (100%) rename CarManagerV3/{ => Manager}/ImageManager.cs (100%) rename CarManagerV3/{ => Manager}/SafeManager.cs (100%) rename CarManagerV3/{ => Manager}/StateManager.cs (100%) diff --git a/CarManagerV3/CarManagerV3.csproj b/CarManagerV3/CarManagerV3.csproj index 0dcc141..ac2735a 100644 --- a/CarManagerV3/CarManagerV3.csproj +++ b/CarManagerV3/CarManagerV3.csproj @@ -61,47 +61,48 @@ - - + + UserControl - + CarCard.cs - - + + Form - + MainForm.cs - + Form - + CarDetailsForm.cs - - + + Form - + PleaseWait.cs - - - + + + + CarCard.cs - + MainForm.cs - + CarDetailsForm.cs - + PleaseWait.cs @@ -139,8 +140,6 @@ false - - - + \ No newline at end of file diff --git a/CarManagerV3/Car.cs b/CarManagerV3/Classes/Car.cs similarity index 100% rename from CarManagerV3/Car.cs rename to CarManagerV3/Classes/Car.cs diff --git a/CarManagerV3/LegacyException.cs b/CarManagerV3/Exceptions/LegacyException.cs similarity index 100% rename from CarManagerV3/LegacyException.cs rename to CarManagerV3/Exceptions/LegacyException.cs diff --git a/CarManagerV3/CarDetailsForm.Designer.cs b/CarManagerV3/Forms/CarDetailsForm.Designer.cs similarity index 100% rename from CarManagerV3/CarDetailsForm.Designer.cs rename to CarManagerV3/Forms/CarDetailsForm.Designer.cs diff --git a/CarManagerV3/CarDetailsForm.cs b/CarManagerV3/Forms/CarDetailsForm.cs similarity index 100% rename from CarManagerV3/CarDetailsForm.cs rename to CarManagerV3/Forms/CarDetailsForm.cs diff --git a/CarManagerV3/CarDetailsForm.resx b/CarManagerV3/Forms/CarDetailsForm.resx similarity index 100% rename from CarManagerV3/CarDetailsForm.resx rename to CarManagerV3/Forms/CarDetailsForm.resx diff --git a/CarManagerV3/CarCard.Designer.cs b/CarManagerV3/Forms/Components/CarCard.Designer.cs similarity index 100% rename from CarManagerV3/CarCard.Designer.cs rename to CarManagerV3/Forms/Components/CarCard.Designer.cs diff --git a/CarManagerV3/CarCard.cs b/CarManagerV3/Forms/Components/CarCard.cs similarity index 100% rename from CarManagerV3/CarCard.cs rename to CarManagerV3/Forms/Components/CarCard.cs diff --git a/CarManagerV3/CarCard.resx b/CarManagerV3/Forms/Components/CarCard.resx similarity index 100% rename from CarManagerV3/CarCard.resx rename to CarManagerV3/Forms/Components/CarCard.resx diff --git a/CarManagerV3/MainForm.Designer.cs b/CarManagerV3/Forms/MainForm.Designer.cs similarity index 98% rename from CarManagerV3/MainForm.Designer.cs rename to CarManagerV3/Forms/MainForm.Designer.cs index 78f8250..fcba4da 100644 --- a/CarManagerV3/MainForm.Designer.cs +++ b/CarManagerV3/Forms/MainForm.Designer.cs @@ -70,7 +70,7 @@ this.flpCars.AutoScroll = true; this.flpCars.AutoScrollMargin = new System.Drawing.Size(0, 200); this.flpCars.Dock = System.Windows.Forms.DockStyle.Fill; - this.flpCars.Location = new System.Drawing.Point(3, 71); + this.flpCars.Location = new System.Drawing.Point(3, 67); this.flpCars.Name = "flpCars"; this.flpCars.Size = new System.Drawing.Size(796, 412); this.flpCars.TabIndex = 1; @@ -83,7 +83,7 @@ this.tableLayoutPanel2.Controls.Add(this.tbxSearch, 0, 0); this.tableLayoutPanel2.Controls.Add(this.btnNewCar, 1, 0); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; - this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 31); + this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 27); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 1; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); @@ -117,7 +117,7 @@ this.fileToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; - this.menuStrip1.Size = new System.Drawing.Size(802, 28); + this.menuStrip1.Size = new System.Drawing.Size(802, 24); this.menuStrip1.TabIndex = 3; this.menuStrip1.Text = "menuStrip1"; // @@ -131,48 +131,48 @@ this.recentFilesToolStripMenuItem, this.revealInFileExplorerToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; - this.fileToolStripMenuItem.Size = new System.Drawing.Size(46, 24); + this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // openToolStripMenuItem // this.openToolStripMenuItem.Name = "openToolStripMenuItem"; - this.openToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + this.openToolStripMenuItem.Size = new System.Drawing.Size(187, 22); this.openToolStripMenuItem.Text = "Open"; this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); // // saveToolStripMenuItem // this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; - this.saveToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + this.saveToolStripMenuItem.Size = new System.Drawing.Size(187, 22); this.saveToolStripMenuItem.Text = "Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // saveAsToolStripMenuItem // this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; - this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(187, 22); this.saveAsToolStripMenuItem.Text = "Save as"; this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click); // // importToolStripMenuItem // this.importToolStripMenuItem.Name = "importToolStripMenuItem"; - this.importToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + this.importToolStripMenuItem.Size = new System.Drawing.Size(187, 22); this.importToolStripMenuItem.Text = "Import"; this.importToolStripMenuItem.Click += new System.EventHandler(this.importToolStripMenuItem_Click); // // recentFilesToolStripMenuItem // this.recentFilesToolStripMenuItem.Name = "recentFilesToolStripMenuItem"; - this.recentFilesToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + this.recentFilesToolStripMenuItem.Size = new System.Drawing.Size(187, 22); this.recentFilesToolStripMenuItem.Text = "Recent Files"; this.recentFilesToolStripMenuItem.Click += new System.EventHandler(this.recentFilesToolStripMenuItem_Click); // // revealInFileExplorerToolStripMenuItem // this.revealInFileExplorerToolStripMenuItem.Name = "revealInFileExplorerToolStripMenuItem"; - this.revealInFileExplorerToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + this.revealInFileExplorerToolStripMenuItem.Size = new System.Drawing.Size(187, 22); this.revealInFileExplorerToolStripMenuItem.Text = "Reveal in File Explorer"; this.revealInFileExplorerToolStripMenuItem.Click += new System.EventHandler(this.revealInFileExplorerToolStripMenuItem_Click); // diff --git a/CarManagerV3/MainForm.cs b/CarManagerV3/Forms/MainForm.cs similarity index 100% rename from CarManagerV3/MainForm.cs rename to CarManagerV3/Forms/MainForm.cs diff --git a/CarManagerV3/MainForm.resx b/CarManagerV3/Forms/MainForm.resx similarity index 100% rename from CarManagerV3/MainForm.resx rename to CarManagerV3/Forms/MainForm.resx diff --git a/CarManagerV3/PleaseWait.Designer.cs b/CarManagerV3/Forms/Util/PleaseWait.Designer.cs similarity index 100% rename from CarManagerV3/PleaseWait.Designer.cs rename to CarManagerV3/Forms/Util/PleaseWait.Designer.cs diff --git a/CarManagerV3/PleaseWait.cs b/CarManagerV3/Forms/Util/PleaseWait.cs similarity index 100% rename from CarManagerV3/PleaseWait.cs rename to CarManagerV3/Forms/Util/PleaseWait.cs diff --git a/CarManagerV3/PleaseWait.resx b/CarManagerV3/Forms/Util/PleaseWait.resx similarity index 100% rename from CarManagerV3/PleaseWait.resx rename to CarManagerV3/Forms/Util/PleaseWait.resx diff --git a/CarManagerV3/ImageManager.cs b/CarManagerV3/Manager/ImageManager.cs similarity index 100% rename from CarManagerV3/ImageManager.cs rename to CarManagerV3/Manager/ImageManager.cs diff --git a/CarManagerV3/SafeManager.cs b/CarManagerV3/Manager/SafeManager.cs similarity index 100% rename from CarManagerV3/SafeManager.cs rename to CarManagerV3/Manager/SafeManager.cs diff --git a/CarManagerV3/StateManager.cs b/CarManagerV3/Manager/StateManager.cs similarity index 100% rename from CarManagerV3/StateManager.cs rename to CarManagerV3/Manager/StateManager.cs From 9b261dbf78edab33f29b8be78238b5ed57ba52b7 Mon Sep 17 00:00:00 2001 From: Frozd Date: Mon, 2 Mar 2026 16:26:17 +0100 Subject: [PATCH 4/5] chore: updated to .NET 8.0 --- CarManagerV3/CarManagerV3.csproj | 119 ++---------------- CarManagerV3/Forms/MainForm.cs | 13 +- CarManagerV3/Properties/AssemblyInfo.cs | 33 ----- CarManagerV3/Properties/Resources.Designer.cs | 2 +- 4 files changed, 16 insertions(+), 151 deletions(-) delete mode 100644 CarManagerV3/Properties/AssemblyInfo.cs diff --git a/CarManagerV3/CarManagerV3.csproj b/CarManagerV3/CarManagerV3.csproj index ac2735a..ca18198 100644 --- a/CarManagerV3/CarManagerV3.csproj +++ b/CarManagerV3/CarManagerV3.csproj @@ -1,17 +1,7 @@ - - - + - Debug - AnyCPU - {93CA258B-A645-41A8-A24F-59036ABC173F} + net8.0-windows WinExe - CarManagerV3 - CarManagerV3 - v4.7.2 - 512 - true - true publish\ true Disk @@ -27,106 +17,17 @@ false false true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 + false + true + true - - - - - - - - - - - - - - - + UserControl - - CarCard.cs - - - - Form - - - MainForm.cs - - - Form - - - CarDetailsForm.cs - - - - Form - - - PleaseWait.cs - - - - - - - - CarCard.cs - - - MainForm.cs - - - CarDetailsForm.cs - - - PleaseWait.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - True - Settings.settings - True - - - - + + + @@ -140,6 +41,4 @@ false - - \ No newline at end of file diff --git a/CarManagerV3/Forms/MainForm.cs b/CarManagerV3/Forms/MainForm.cs index e5dd190..257ff5b 100644 --- a/CarManagerV3/Forms/MainForm.cs +++ b/CarManagerV3/Forms/MainForm.cs @@ -127,8 +127,8 @@ namespace CarManagerV3 detailsForm.ShowDialog(); }; - ContextMenu cm = new ContextMenu(); - cm.MenuItems.Add(new MenuItem("Move Up", (s, e) => + ContextMenuStrip cms = new ContextMenuStrip(); + cms.Items.Add("Move up", null, (s, e) => { int order = car.Order; // find car with order just less than this one @@ -142,11 +142,10 @@ namespace CarManagerV3 SafeManager.SaveCars(filepath, cars); refreshCars(cars); } - })); + }); - cm.MenuItems.Add(new MenuItem("Move Down", (s, e) => + cms.Items.Add("Move down", null, (s, e) => { - int order = car.Order; // find car with order just greater than this one Car other = cars.Where(c => c.Order > order).OrderBy(c => c.Order).FirstOrDefault(); @@ -159,9 +158,9 @@ namespace CarManagerV3 SafeManager.SaveCars(filepath, cars); refreshCars(cars); } - })); + }); - card.ContextMenu = cm; + card.ContextMenuStrip = cms; if (isNew) { diff --git a/CarManagerV3/Properties/AssemblyInfo.cs b/CarManagerV3/Properties/AssemblyInfo.cs deleted file mode 100644 index f356216..0000000 --- a/CarManagerV3/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("CarManagerV3")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("CarManagerV3")] -[assembly: AssemblyCopyright("Copyright © 2025")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("93ca258b-a645-41a8-a24f-59036abc173f")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/CarManagerV3/Properties/Resources.Designer.cs b/CarManagerV3/Properties/Resources.Designer.cs index 54ae591..ad07e6f 100644 --- a/CarManagerV3/Properties/Resources.Designer.cs +++ b/CarManagerV3/Properties/Resources.Designer.cs @@ -19,7 +19,7 @@ namespace CarManagerV3.Properties { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "18.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { From f0d51bc85ea6325e8c21f09e88060b0e100774d9 Mon Sep 17 00:00:00 2001 From: Frozd Date: Mon, 2 Mar 2026 16:34:18 +0100 Subject: [PATCH 5/5] feat: CUID & fix: reorder bug --- CarManagerV3/Classes/Car.cs | 8 +- CarManagerV3/Forms/MainForm.Designer.cs | 245 ++++++++++++------------ CarManagerV3/Forms/MainForm.cs | 2 + CarManagerV3/Forms/MainForm.resx | 54 +++--- CarManagerV3/Util/CUID.cs | 118 ++++++++++++ 5 files changed, 275 insertions(+), 152 deletions(-) create mode 100644 CarManagerV3/Util/CUID.cs diff --git a/CarManagerV3/Classes/Car.cs b/CarManagerV3/Classes/Car.cs index 431da59..599bd1e 100644 --- a/CarManagerV3/Classes/Car.cs +++ b/CarManagerV3/Classes/Car.cs @@ -1,4 +1,5 @@ using System; +using CarManagerV3.Util; namespace CarManagerV3 { @@ -115,12 +116,15 @@ namespace CarManagerV3 int numericId = 0; if ((string.IsNullOrWhiteSpace(id) || int.TryParse(id, out numericId)) && id != "0") { - id = Guid.NewGuid().ToString(); + id = CUID.NewCUID().ToString(); if (numericId > 0) { order = numericId + order; } - + } + if(id.Length > 8) + { + id = CUID.NewCUID().ToString(); } // Sets the properties using the setters to ensure validation is applied. this.id = id; diff --git a/CarManagerV3/Forms/MainForm.Designer.cs b/CarManagerV3/Forms/MainForm.Designer.cs index fcba4da..52d8aad 100644 --- a/CarManagerV3/Forms/MainForm.Designer.cs +++ b/CarManagerV3/Forms/MainForm.Designer.cs @@ -29,171 +29,170 @@ private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); - this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); - this.flpCars = new System.Windows.Forms.FlowLayoutPanel(); - this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); - this.tbxSearch = new System.Windows.Forms.TextBox(); - this.btnNewCar = new System.Windows.Forms.Button(); - this.menuStrip1 = new System.Windows.Forms.MenuStrip(); - this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.importToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.recentFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.revealInFileExplorerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.tableLayoutPanel1.SuspendLayout(); - this.tableLayoutPanel2.SuspendLayout(); - this.menuStrip1.SuspendLayout(); - this.SuspendLayout(); + tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + flpCars = new System.Windows.Forms.FlowLayoutPanel(); + tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); + tbxSearch = new System.Windows.Forms.TextBox(); + btnNewCar = new System.Windows.Forms.Button(); + menuStrip1 = new System.Windows.Forms.MenuStrip(); + fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + importToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + recentFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + revealInFileExplorerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + tableLayoutPanel1.SuspendLayout(); + tableLayoutPanel2.SuspendLayout(); + menuStrip1.SuspendLayout(); + SuspendLayout(); // // tableLayoutPanel1 // - this.tableLayoutPanel1.ColumnCount = 1; - this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel1.Controls.Add(this.flpCars, 0, 2); - this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 1); - this.tableLayoutPanel1.Controls.Add(this.menuStrip1, 0, 0); - this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; - this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); - this.tableLayoutPanel1.Name = "tableLayoutPanel1"; - this.tableLayoutPanel1.RowCount = 3; - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F)); - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.Size = new System.Drawing.Size(802, 458); - this.tableLayoutPanel1.TabIndex = 0; - this.tableLayoutPanel1.Paint += new System.Windows.Forms.PaintEventHandler(this.tableLayoutPanel1_Paint); + tableLayoutPanel1.ColumnCount = 1; + tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + tableLayoutPanel1.Controls.Add(flpCars, 0, 2); + tableLayoutPanel1.Controls.Add(tableLayoutPanel2, 0, 1); + tableLayoutPanel1.Controls.Add(menuStrip1, 0, 0); + tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; + tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); + tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + tableLayoutPanel1.Name = "tableLayoutPanel1"; + tableLayoutPanel1.RowCount = 3; + tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F)); + tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + tableLayoutPanel1.Size = new System.Drawing.Size(802, 572); + tableLayoutPanel1.TabIndex = 0; + tableLayoutPanel1.Paint += tableLayoutPanel1_Paint; // // flpCars // - this.flpCars.AutoScroll = true; - this.flpCars.AutoScrollMargin = new System.Drawing.Size(0, 200); - this.flpCars.Dock = System.Windows.Forms.DockStyle.Fill; - this.flpCars.Location = new System.Drawing.Point(3, 67); - this.flpCars.Name = "flpCars"; - this.flpCars.Size = new System.Drawing.Size(796, 412); - this.flpCars.TabIndex = 1; + flpCars.AutoScroll = true; + flpCars.AutoScrollMargin = new System.Drawing.Size(0, 200); + flpCars.Dock = System.Windows.Forms.DockStyle.Fill; + flpCars.Location = new System.Drawing.Point(3, 82); + flpCars.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + flpCars.Name = "flpCars"; + flpCars.Size = new System.Drawing.Size(796, 515); + flpCars.TabIndex = 1; // // tableLayoutPanel2 // - this.tableLayoutPanel2.ColumnCount = 2; - this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); - this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); - this.tableLayoutPanel2.Controls.Add(this.tbxSearch, 0, 0); - this.tableLayoutPanel2.Controls.Add(this.btnNewCar, 1, 0); - this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; - this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 27); - this.tableLayoutPanel2.Name = "tableLayoutPanel2"; - this.tableLayoutPanel2.RowCount = 1; - this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 34F)); - this.tableLayoutPanel2.Size = new System.Drawing.Size(796, 34); - this.tableLayoutPanel2.TabIndex = 2; + tableLayoutPanel2.ColumnCount = 2; + tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + tableLayoutPanel2.Controls.Add(tbxSearch, 0, 0); + tableLayoutPanel2.Controls.Add(btnNewCar, 1, 0); + tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; + tableLayoutPanel2.Location = new System.Drawing.Point(3, 32); + tableLayoutPanel2.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + tableLayoutPanel2.Name = "tableLayoutPanel2"; + tableLayoutPanel2.RowCount = 1; + tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 42F)); + tableLayoutPanel2.Size = new System.Drawing.Size(796, 42); + tableLayoutPanel2.TabIndex = 2; // // tbxSearch // - this.tbxSearch.Dock = System.Windows.Forms.DockStyle.Fill; - this.tbxSearch.Location = new System.Drawing.Point(3, 3); - this.tbxSearch.Name = "tbxSearch"; - this.tbxSearch.Size = new System.Drawing.Size(392, 22); - this.tbxSearch.TabIndex = 3; - this.tbxSearch.TextChanged += new System.EventHandler(this.tbxSearch_TextChanged); + tbxSearch.Dock = System.Windows.Forms.DockStyle.Fill; + tbxSearch.Location = new System.Drawing.Point(3, 4); + tbxSearch.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + tbxSearch.Name = "tbxSearch"; + tbxSearch.Size = new System.Drawing.Size(392, 27); + tbxSearch.TabIndex = 3; + tbxSearch.TextChanged += tbxSearch_TextChanged; // // btnNewCar // - this.btnNewCar.Location = new System.Drawing.Point(401, 3); - this.btnNewCar.Name = "btnNewCar"; - this.btnNewCar.Size = new System.Drawing.Size(75, 23); - this.btnNewCar.TabIndex = 4; - this.btnNewCar.Text = "Add Car"; - this.btnNewCar.UseVisualStyleBackColor = true; - this.btnNewCar.Click += new System.EventHandler(this.btnNewCar_Click); + btnNewCar.Location = new System.Drawing.Point(401, 4); + btnNewCar.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + btnNewCar.Name = "btnNewCar"; + btnNewCar.Size = new System.Drawing.Size(75, 29); + btnNewCar.TabIndex = 4; + btnNewCar.Text = "Add Car"; + btnNewCar.UseVisualStyleBackColor = true; + btnNewCar.Click += btnNewCar_Click; // // menuStrip1 // - this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); - this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.fileToolStripMenuItem}); - this.menuStrip1.Location = new System.Drawing.Point(0, 0); - this.menuStrip1.Name = "menuStrip1"; - this.menuStrip1.Size = new System.Drawing.Size(802, 24); - this.menuStrip1.TabIndex = 3; - this.menuStrip1.Text = "menuStrip1"; + menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); + menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { fileToolStripMenuItem }); + menuStrip1.Location = new System.Drawing.Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new System.Drawing.Size(802, 28); + menuStrip1.TabIndex = 3; + menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // - this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.openToolStripMenuItem, - this.saveToolStripMenuItem, - this.saveAsToolStripMenuItem, - this.importToolStripMenuItem, - this.recentFilesToolStripMenuItem, - this.revealInFileExplorerToolStripMenuItem}); - this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; - this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); - this.fileToolStripMenuItem.Text = "File"; + fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { openToolStripMenuItem, saveToolStripMenuItem, saveAsToolStripMenuItem, importToolStripMenuItem, recentFilesToolStripMenuItem, revealInFileExplorerToolStripMenuItem }); + fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + fileToolStripMenuItem.Size = new System.Drawing.Size(46, 24); + fileToolStripMenuItem.Text = "File"; // // openToolStripMenuItem // - this.openToolStripMenuItem.Name = "openToolStripMenuItem"; - this.openToolStripMenuItem.Size = new System.Drawing.Size(187, 22); - this.openToolStripMenuItem.Text = "Open"; - this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); + openToolStripMenuItem.Name = "openToolStripMenuItem"; + openToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + openToolStripMenuItem.Text = "Open"; + openToolStripMenuItem.Click += openToolStripMenuItem_Click; // // saveToolStripMenuItem // - this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; - this.saveToolStripMenuItem.Size = new System.Drawing.Size(187, 22); - this.saveToolStripMenuItem.Text = "Save"; - this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + saveToolStripMenuItem.Text = "Save"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; // // saveAsToolStripMenuItem // - this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; - this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(187, 22); - this.saveAsToolStripMenuItem.Text = "Save as"; - this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click); + saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; + saveAsToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + saveAsToolStripMenuItem.Text = "Save as"; + saveAsToolStripMenuItem.Click += saveAsToolStripMenuItem_Click; // // importToolStripMenuItem // - this.importToolStripMenuItem.Name = "importToolStripMenuItem"; - this.importToolStripMenuItem.Size = new System.Drawing.Size(187, 22); - this.importToolStripMenuItem.Text = "Import"; - this.importToolStripMenuItem.Click += new System.EventHandler(this.importToolStripMenuItem_Click); + importToolStripMenuItem.Name = "importToolStripMenuItem"; + importToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + importToolStripMenuItem.Text = "Import"; + importToolStripMenuItem.Click += importToolStripMenuItem_Click; // // recentFilesToolStripMenuItem // - this.recentFilesToolStripMenuItem.Name = "recentFilesToolStripMenuItem"; - this.recentFilesToolStripMenuItem.Size = new System.Drawing.Size(187, 22); - this.recentFilesToolStripMenuItem.Text = "Recent Files"; - this.recentFilesToolStripMenuItem.Click += new System.EventHandler(this.recentFilesToolStripMenuItem_Click); + recentFilesToolStripMenuItem.Name = "recentFilesToolStripMenuItem"; + recentFilesToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + recentFilesToolStripMenuItem.Text = "Recent Files"; + recentFilesToolStripMenuItem.Click += recentFilesToolStripMenuItem_Click; // // revealInFileExplorerToolStripMenuItem // - this.revealInFileExplorerToolStripMenuItem.Name = "revealInFileExplorerToolStripMenuItem"; - this.revealInFileExplorerToolStripMenuItem.Size = new System.Drawing.Size(187, 22); - this.revealInFileExplorerToolStripMenuItem.Text = "Reveal in File Explorer"; - this.revealInFileExplorerToolStripMenuItem.Click += new System.EventHandler(this.revealInFileExplorerToolStripMenuItem_Click); + revealInFileExplorerToolStripMenuItem.Name = "revealInFileExplorerToolStripMenuItem"; + revealInFileExplorerToolStripMenuItem.Size = new System.Drawing.Size(238, 26); + revealInFileExplorerToolStripMenuItem.Text = "Reveal in File Explorer"; + revealInFileExplorerToolStripMenuItem.Click += revealInFileExplorerToolStripMenuItem_Click; // // MainForm // - this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(802, 458); - this.Controls.Add(this.tableLayoutPanel1); - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MainMenuStrip = this.menuStrip1; - this.MinimumSize = new System.Drawing.Size(818, 497); - this.Name = "MainForm"; - this.Text = "Carmanager 3"; - this.tableLayoutPanel1.ResumeLayout(false); - this.tableLayoutPanel1.PerformLayout(); - this.tableLayoutPanel2.ResumeLayout(false); - this.tableLayoutPanel2.PerformLayout(); - this.menuStrip1.ResumeLayout(false); - this.menuStrip1.PerformLayout(); - this.ResumeLayout(false); + AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + ClientSize = new System.Drawing.Size(802, 572); + Controls.Add(tableLayoutPanel1); + Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); + MainMenuStrip = menuStrip1; + Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + MinimumSize = new System.Drawing.Size(818, 609); + Name = "MainForm"; + Text = "Carmanager 3"; + tableLayoutPanel1.ResumeLayout(false); + tableLayoutPanel1.PerformLayout(); + tableLayoutPanel2.ResumeLayout(false); + tableLayoutPanel2.PerformLayout(); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ResumeLayout(false); } diff --git a/CarManagerV3/Forms/MainForm.cs b/CarManagerV3/Forms/MainForm.cs index 257ff5b..5366660 100644 --- a/CarManagerV3/Forms/MainForm.cs +++ b/CarManagerV3/Forms/MainForm.cs @@ -139,6 +139,7 @@ namespace CarManagerV3 int temp = car.Order; car.Order = other.Order; other.Order = temp; + cars = StateManager.normalizeOrders(cars); SafeManager.SaveCars(filepath, cars); refreshCars(cars); } @@ -155,6 +156,7 @@ namespace CarManagerV3 int temp = car.Order; car.Order = other.Order; other.Order = temp; + cars = StateManager.normalizeOrders(cars); SafeManager.SaveCars(filepath, cars); refreshCars(cars); } diff --git a/CarManagerV3/Forms/MainForm.resx b/CarManagerV3/Forms/MainForm.resx index bb1bb0c..aaace22 100644 --- a/CarManagerV3/Forms/MainForm.resx +++ b/CarManagerV3/Forms/MainForm.resx @@ -1,17 +1,17 @@  - diff --git a/CarManagerV3/Util/CUID.cs b/CarManagerV3/Util/CUID.cs new file mode 100644 index 0000000..12e6901 --- /dev/null +++ b/CarManagerV3/Util/CUID.cs @@ -0,0 +1,118 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace CarManagerV3.Util +{ + internal class CUID + { + public const int DefaultLength = 6; + + private static int _counter = RandomNumberGenerator.GetInt32(int.MaxValue); + + /// + /// Generate a random CUID (Collision-resistant Unique Identifier) of a specified length. + /// The CUID is designed to be unique across different machines and time, making it suitable for use as an identifier for cars in the application. + /// The length must be between 4 and 32 characters to ensure a good balance between uniqueness and readability. + /// The generated CUID consists of a combination of alphanumeric characters to ensure uniqueness and readability. + /// + /// The desired length of the generated CUID + /// Whether to prefix the CUID with 'c' for better readability and to avoid starting with a digit." + /// + public static string NewCUID(int length = DefaultLength, bool prefixWithC = true) + { + // CUIDv2 specs allow between 4 and 32 chars. + if(length < 4 || length > 32) throw new ArgumentOutOfRangeException("length"); + + // We will produce enough encoded chars to satisfy 'length' after prefixing and truncation. + // Base64 encodes 3 bytes -> 4 chars. So bytesNeeded ≈ ceil(charsNeeded * 3/4). + int charsNeeded = prefixWithC ? (length - 1) : length; + int bytesNeeded = (int)Math.Ceiling(charsNeeded * 3.0 / 4.0); + + Span material = stackalloc byte[32]; + FillMaterial(material); + + byte[] outputBytes = ExpandWithSha256(material, bytesNeeded); + + string encoded = Base64UrlEncode(outputBytes); + + if (encoded.Length < charsNeeded) + { + // Extremely unlikely unless length is huge; ensure we have enough by expanding more. + // (Kept as a guard; for typical lengths like 24-64, you're fine.) + outputBytes = ExpandWithSha256(material, bytesNeeded + 32); + encoded = Base64UrlEncode(outputBytes); + } + + string body = encoded.Substring(0, charsNeeded); + return prefixWithC ? ("c" + body) : body; + + } + + + private static void FillMaterial(Span dst32) + { + // Compose a payload with: + // - 16 bytes random + // - 8 bytes timestamp (UTC ticks) + // - 4 bytes counter + // - 4 bytes process/thread noise + Span payload = stackalloc byte[16 + 8 + 4 + 4]; + + RandomNumberGenerator.Fill(payload.Slice(0, 16)); + + long ticks = DateTime.UtcNow.Ticks; + BinaryPrimitives.WriteInt64LittleEndian(payload.Slice(16, 8), ticks); + + int c = Interlocked.Increment(ref _counter); + BinaryPrimitives.WriteInt32LittleEndian(payload.Slice(24, 4), c); + + // Some extra variability (not relied on for security) + int noise = Environment.ProcessId ^ Thread.CurrentThread.ManagedThreadId ^ (int)Stopwatch.GetTimestamp(); + BinaryPrimitives.WriteInt32LittleEndian(payload.Slice(28, 4), noise); + + // Hash to produce 32 bytes of uniformly distributed output + SHA256.HashData(payload, dst32); + } + + private static byte[] ExpandWithSha256(ReadOnlySpan seed32, int bytesNeeded) + { + if (bytesNeeded <= 0) return Array.Empty(); + + // If <= 32 bytes, we can just take from seed32 by hashing once more for separation. + // We'll use SHA256(seed || blockIndex) to generate blocks. + int blocks = (int)Math.Ceiling(bytesNeeded / 32.0); + byte[] result = new byte[blocks * 32]; + + Span input = stackalloc byte[32 + 4]; + seed32.CopyTo(input.Slice(0, 32)); + + for (int i = 0; i < blocks; i++) + { + BinaryPrimitives.WriteInt32LittleEndian(input.Slice(32, 4), i); + Span block = result.AsSpan(i * 32, 32); + SHA256.HashData(input, block); + } + + if (result.Length == bytesNeeded) return result; + + byte[] trimmed = new byte[bytesNeeded]; + Buffer.BlockCopy(result, 0, trimmed, 0, bytesNeeded); + return trimmed; + } + + private static string Base64UrlEncode(byte[] bytes) + { + // Standard base64url without padding per RFC 4648 §5 + string b64 = Convert.ToBase64String(bytes); + return b64.Replace('+', '-').Replace('/', '_').TrimEnd('='); + } + + } +}