From 95892d4f59a4d693e96d49d87695666575a52618 Mon Sep 17 00:00:00 2001 From: Kristina Date: Sun, 10 Dec 2023 21:24:28 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B7=D0=B0=D1=84=D0=B8=D0=BA=D1=81=D0=B8?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B0=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectBoat_bae/BoatDelegate.cs | 2 +- .../ProjectBoat_bae/ExtentionBoat.cs | 2 +- .../ProjectBoat_bae/FormBoatCollection.cs | 237 +++++++++++++----- .../ProjectBoat_bae/FormBoatConfig.cs | 22 +- .../Generics/BoatsGenericCollection.cs | 3 +- .../Generics/BoatsGenericStorage.cs | 149 ++++++++--- 6 files changed, 307 insertions(+), 108 deletions(-) diff --git a/ProjectBoat_base/ProjectBoat_bae/BoatDelegate.cs b/ProjectBoat_base/ProjectBoat_bae/BoatDelegate.cs index 4bae00b..4e32984 100644 --- a/ProjectBoat_base/ProjectBoat_bae/BoatDelegate.cs +++ b/ProjectBoat_base/ProjectBoat_bae/BoatDelegate.cs @@ -9,7 +9,7 @@ namespace ProjectBoat_bae { internal class BoatDelegate { - // Делегат для передачи объекта-автомобиля + // Делегат для передачи объекта public delegate void boatDelegate(Drawningboat boat); } } diff --git a/ProjectBoat_base/ProjectBoat_bae/ExtentionBoat.cs b/ProjectBoat_base/ProjectBoat_bae/ExtentionBoat.cs index 2503329..ebeb082 100644 --- a/ProjectBoat_base/ProjectBoat_bae/ExtentionBoat.cs +++ b/ProjectBoat_base/ProjectBoat_bae/ExtentionBoat.cs @@ -10,7 +10,7 @@ using ProjectBoat_bae.Entities; namespace ProjectBoat_bae { - internal static class ExtentionCar + internal static class ExtentionBoat { // Разделитель для записи информации по объекту в файл private static readonly char _separatorForObject = ':'; diff --git a/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.cs b/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.cs index e9a41c4..7d17853 100644 --- a/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.cs +++ b/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.cs @@ -1,4 +1,6 @@ -using System; +using Microsoft.Extensions.Logging; + +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -7,12 +9,12 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -using Microsoft.Extensions.Logging; using ProjectBoat_bae.DrawningObjects; using ProjectBoat_bae.Generics; using ProjectBoat_bae.Exceptions; - +using ProjectBoat_bae.MovementStrategy; +using NLog; namespace ProjectBoat_bae { @@ -22,9 +24,9 @@ namespace ProjectBoat_bae private readonly BoatsGenericStorage _storage; // Логер - private readonly ILogger _logger; + private readonly Microsoft.Extensions.Logging.ILogger? _logger; - public FormBoatCollection() + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); @@ -72,7 +74,7 @@ namespace ProjectBoat_bae } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); - _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); + _logger.LogInformation($"Added set: {textBoxStorageName.Text}"); } // Удаление набора @@ -95,71 +97,143 @@ namespace ProjectBoat_bae { _storage.DelSet(name); ReloadObjects(); - _logger.LogInformation($"Удален набор: {name}"); + _logger.LogInformation($"Deleted set: {name}"); } } // Добавление объекта в набор private void ButtonAddBoat_Click(object sender, EventArgs e) { - if (listBoxStorages.SelectedIndex == -1) return; + //if (listBoxStorages.SelectedIndex == -1) return; + //var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + //if (obj == null) return; + + //FormBoatConfig form = new FormBoatConfig(); + //form.AddEvent(AddBoat); + //form.Show(); + if (listBoxStorages.SelectedIndex == -1) + { + return; + } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; - if (obj == null) return; - - FormBoatConfig form = new FormBoatConfig(); - - form.AddEvent(AddBoat); - form.Show(); + if (obj == null) + { + return; + } + FormBoatConfig formPlaneConfig = new FormBoatConfig(); + formPlaneConfig.AddEvent(AddBoat); + formPlaneConfig.Show(); } private void AddBoat(Drawningboat boat) { - boat._pictureWidth = pictureBoxCollection.Width; - boat._pictureHeight = pictureBoxCollection.Height; - if (listBoxStorages.SelectedIndex == -1) return; - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; - if (obj == null) return; + //boat._pictureWidth = pictureBoxCollection.Width; + //boat._pictureHeight = pictureBoxCollection.Height; + //if (listBoxStorages.SelectedIndex == -1) return; + //var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + //if (obj == null) return; - if (obj + boat) + //if (obj + boat) + //{ + // MessageBox.Show("Объект добавлен"); + // pictureBoxCollection.Image = obj.ShowBoats(); + //} + //else + //{ + // MessageBox.Show("Не удалось добавить объект"); + //} + if (listBoxStorages.SelectedIndex == -1) { + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + { + _logger.LogWarning("Добавление пустого объекта"); + return; + } + try + { + _ = obj + boat; MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowBoats(); + _logger.LogInformation($"boat added {listBoxStorages.SelectedItem.ToString()}"); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"boat not added {listBoxStorages.SelectedItem.ToString()}"); } } //удаление объекта private void ButtonRemoveBoat_Click(object sender, EventArgs e) { + //if (listBoxStorages.SelectedIndex == -1) + //{ + // return; + //} + //var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? + //string.Empty]; + //if (obj == null) + //{ + // return; + //} + //if (MessageBox.Show("Удалить объект?", "Удаление", + //MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + //{ + // return; + //} + //int pos = 0; + //if (textBoxBoat != null) + // pos = Convert.ToInt32(textBoxBoat.Text); + //if (obj - pos != null) + //{ + // MessageBox.Show("Объект удален"); + // pictureBoxCollection.Image = obj.ShowBoats(); + //} + //else + //{ + // MessageBox.Show("Не удалось удалить объект"); + //} if (listBoxStorages.SelectedIndex == -1) { return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + if (MessageBox.Show("Удалить объект?", "Удалить", MessageBoxButtons.YesNo, + MessageBoxIcon.Question) == DialogResult.No) { return; } - int pos = 0; - if (textBoxBoat != null) - pos = Convert.ToInt32(textBoxBoat.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowBoats(); + int pos = Convert.ToInt32(textBoxBoat.Text); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowBoats(); + _logger.LogInformation($"лодка удалена из набора {listBoxStorages.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Объект не удален"); + _logger.LogWarning($"лодка не удалена из набора {listBoxStorages.SelectedItem.ToString()}"); + } } - else + catch (BoatNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"BoatNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show("Объект не добавлен"); + _logger.LogWarning("Not input"); } } @@ -189,18 +263,47 @@ namespace ProjectBoat_bae //сохранение private void SaveToolStripMenu_Click(object sender, EventArgs e) { + //if (saveFileDialog.ShowDialog() == DialogResult.OK) + //{ + // try + // { + // _storage.SaveData(saveFileDialog.FileName); + // MessageBox.Show("Сохранение прошло успешно", + // "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + // } + // catch (Exception ex) + // { + // MessageBox.Show($"Не сохранилось: {ex.Message}", + // "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + // } + //} + //if (saveFileDialog.ShowDialog() == DialogResult.OK) + //{ + // try + // { + // _storage.SaveData(saveFileDialog.FileName); + // MessageBox.Show("Сохранение завершено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + // _logger.LogInformation($"save in file {saveFileDialog.FileName}"); + // } + // catch (Exception ex) + // { + // MessageBox.Show($"Не сохранено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + // _logger.LogWarning($"Save to file {saveFileDialog.FileName} not complete"); + // } + //} if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { _storage.SaveData(saveFileDialog.FileName); - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogWarning($"Файл {saveFileDialog.FileName} успешно сохранен"); } catch (Exception ex) { - MessageBox.Show($"Не сохранилось: {ex.Message}", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось сохранить"); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } @@ -208,52 +311,56 @@ namespace ProjectBoat_bae //загрузка private void LoadToolStripMenu_Click(object sender, EventArgs args) { + //if (openFileDialog.ShowDialog() == DialogResult.OK) //{ // if (_storage.LoadData(openFileDialog.FileName)) // { - // MessageBox.Show("Load Complete", "Result", - // MessageBoxButtons.OK, MessageBoxIcon.Information); - // ReloadObjects(); + // MessageBox.Show("Загрузка прошла успешно", + // "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); // } // else // { - // MessageBox.Show("Load Not Complete", "Result", - // MessageBoxButtons.OK, MessageBoxIcon.Error); + // MessageBox.Show("Не загрузилось", "Результат", + // MessageBoxButtons.OK, MessageBoxIcon.Error); // } //} - - if (openFileDialog.ShowDialog() == DialogResult.OK) - { - if (_storage.LoadData(openFileDialog.FileName)) - { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else - { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - ReloadObjects(); - + //ReloadObjects(); //if (openFileDialog.ShowDialog() == DialogResult.OK) //{ // try // { // _storage.LoadData(openFileDialog.FileName); - - // MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - // _logger.LogInformation("Загрузка прошла успешно"); + // MessageBox.Show("Загрузка завершена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + // ReloadObjects(); + // _logger.LogInformation($"load from file {openFileDialog.FileName}"); // } // catch (Exception ex) // { - // MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - // _logger.LogWarning($"Не загрузилось: {ex.Message}"); + // MessageBox.Show($"Не загружено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + // _logger.LogWarning($"load from file {openFileDialog.FileName} not complete"); // } //} - //ReloadObjects(); + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storage.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogWarning($"Файл {openFileDialog.FileName} успешно загружен"); + foreach (var collection in _storage.Keys) + { + listBoxStorages.Items.Add(collection); + } + ReloadObjects(); + } + catch (Exception ex) + { + _logger.LogWarning("Не удалось загрузить"); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + + } + } } } } diff --git a/ProjectBoat_base/ProjectBoat_bae/FormBoatConfig.cs b/ProjectBoat_base/ProjectBoat_bae/FormBoatConfig.cs index 9333b3f..7fa604e 100644 --- a/ProjectBoat_base/ProjectBoat_bae/FormBoatConfig.cs +++ b/ProjectBoat_base/ProjectBoat_bae/FormBoatConfig.cs @@ -10,6 +10,10 @@ using System.Windows.Forms; using ProjectBoat_bae.DrawningObjects; using ProjectBoat_bae.Entities; + +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + namespace ProjectBoat_bae { public partial class FormBoatConfig : Form @@ -83,18 +87,28 @@ namespace ProjectBoat_bae // Действия при приеме перетаскиваемой информации private void PanelObject_DragDrop(object sender, DragEventArgs e) { + //switch (e.Data?.GetData(DataFormats.Text).ToString()) + //{ + // case "labelSimpleObject": + // _boat = new Drawningboat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height); + // break; + // case "labelModifiedObject": + // _boat = new DrawningMotorBoat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, + // checkBoxBoat.Checked, checkBoxBoat2.Checked, pictureBoxObject.Width, pictureBoxObject.Height); + // break; + //} + //LabelColor.BackColor = Color.Empty; + //LabelAdditionalColor.BackColor = Color.Empty; + ILogger logger = new NullLogger(); switch (e.Data?.GetData(DataFormats.Text).ToString()) { case "labelSimpleObject": _boat = new Drawningboat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height); break; case "labelModifiedObject": - _boat = new DrawningMotorBoat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, - checkBoxBoat.Checked, checkBoxBoat2.Checked, pictureBoxObject.Width, pictureBoxObject.Height); + _boat = new DrawningMotorBoat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxBoat.Checked, checkBoxBoat2.Checked, pictureBoxObject.Width, pictureBoxObject.Height); break; } - LabelColor.BackColor = Color.Empty; - LabelAdditionalColor.BackColor = Color.Empty; DrawBoat(); } diff --git a/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericCollection.cs b/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericCollection.cs index 6ba6021..12def1a 100644 --- a/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericCollection.cs +++ b/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericCollection.cs @@ -102,7 +102,8 @@ namespace ProjectBoat_bae.Generics T? t = _collection[i]; if (t != null) { - t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight); + t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, + (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight); if (t is Drawningboat) (t as Drawningboat).DrawTransport(g); else t.DrawTransport(g); } diff --git a/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericStorage.cs b/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericStorage.cs index d929294..9f66385 100644 --- a/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericStorage.cs +++ b/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericStorage.cs @@ -52,6 +52,30 @@ namespace ProjectBoat_bae.Generics public void SaveData(string filename) { + //if (File.Exists(filename)) + //{ + // File.Delete(filename); + //} + //StringBuilder data = new(); + //foreach (KeyValuePair> record in _boatStorages) + //{ + // StringBuilder records = new(); + // foreach (Drawningboat? elem in record.Value.GetBoats) + // { + // records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + // } + // data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + //} + //if (data.Length == 0) + //{ + // throw new Exception("Невалиданя операция, нет данных для сохранения"); + //} + //using FileStream fs = new(filename, FileMode.Create); + //byte[] info = new + //UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}"); + //fs.Write(info, 0, info.Length); + //return; if (File.Exists(filename)) { File.Delete(filename); @@ -69,65 +93,118 @@ namespace ProjectBoat_bae.Generics } if (data.Length == 0) { - throw new Exception("Невалиданя операция, нет данных для сохранения"); + throw new Exception("Невалидная операция, нет данных для сохранения"); } using FileStream fs = new(filename, FileMode.Create); byte[] info = new - UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}"); + UTF8Encoding(true).GetBytes($"BusStorage{Environment.NewLine}{data}"); fs.Write(info, 0, info.Length); return; } - public bool LoadData(string filename) + //public bool LoadData(string filename) + public void LoadData(string filename) { + //if (!File.Exists(filename)) + //{ + // return false; + //} + //using (StreamReader fs = File.OpenText(filename)) + //{ + // string str = fs.ReadLine(); + // if (str == null || str.Length == 0) + // { + // return false; + // } + // if (!str.StartsWith("ShipStorage")) + // { + // return false; + // } + + // _boatStorages.Clear(); + // string strs = ""; + + // while ((strs = fs.ReadLine()) != null) + // { + // if (strs == null) + // { + // return false; + // } + + // string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + // if (record.Length != 2) + // { + // continue; + // } + // BoatsGenericCollection collection = new(_pictureWidth, _pictureHeight); + // string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + // foreach (string elem in set) + // { + // Drawningboat? boat = elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight); + // if (boat != null) + // { + // if (!(collection + boat)) + // { + // return false; + // } + // } + // } + // _boatStorages.Add(record[0], collection); + // } + // return true; + //} if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } - using (StreamReader fs = File.OpenText(filename)) + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) { - string str = fs.ReadLine(); - if (str == null || str.Length == 0) + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) { - return false; + bufferTextFromFile += temp.GetString(b); } - if (!str.StartsWith("ShipStorage")) + } + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, + StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + throw new Exception("Нет данных для загрузки"); + } + if (!strs[0].StartsWith("BusStorage")) + { + //если нет такой записи, то это не те данные + throw new Exception("Неверный формат данных"); + } + _boatStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) { - return false; + continue; } - - _boatStorages.Clear(); - string strs = ""; - - while ((strs = fs.ReadLine()) != null) + BoatsGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, + StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) { - if (strs == null) + Drawningboat? boat = + elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight); + if (boat != null) { - return false; - } - - string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) - { - continue; - } - BoatsGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) - { - Drawningboat? boat = elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight); - if (boat != null) + if (!(collection + boat)) { - if (!(collection + boat)) - { - return false; - } + throw new Exception("Ошибка добавления в коллекцию"); } } - _boatStorages.Add(record[0], collection); } - return true; + _boatStorages.Add(record[0], collection); } } }