From 7f7e5253a3f9df2e3c65b54a84c93af330c20670 Mon Sep 17 00:00:00 2001 From: user <732603@gmail.com> Date: Wed, 24 Apr 2024 21:25:45 +0400 Subject: [PATCH 1/8] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=966?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 13 +- .../ListGenericObjects.cs | 24 ++- .../MassiveGenericObjects.cs | 18 +- .../StorageCollection.cs | 159 +++++++++++++++++- .../ProjectMotorBoat/Drawings/DrawingBoat.cs | 7 + .../Drawings/DrawingMotorBoat.cs | 5 + .../Drawings/ExtentionDrawingBoat.cs | 56 ++++++ .../ProjectMotorBoat/Entities/EntityBoat.cs | 30 ++++ .../Entities/EntityMotorBoat.cs | 40 +++++ .../FormBoatCollection.Designer.cs | 78 +++++++-- .../ProjectMotorBoat/FormBoatCollection.cs | 42 +++++ .../ProjectMotorBoat/FormBoatCollection.resx | 9 + 13 files changed, 467 insertions(+), 16 deletions(-) create mode 100644 ProjectMotorBoat/ProjectMotorBoat/Drawings/ExtentionDrawingBoat.cs diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs index 1403f66..5a87d1f 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs @@ -48,7 +48,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs index f5e51e7..b405892 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -15,7 +15,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -45,4 +45,15 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs index ddb1ebe..f815ab9 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs @@ -13,7 +13,21 @@ public class ListGenericObjects : ICollectionGenericObjects public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount { + get + { + return _maxCount; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -68,4 +82,12 @@ public class ListGenericObjects : ICollectionGenericObjects } return null; } + + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs index 27b3f31..27cc790 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -14,8 +14,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -32,6 +36,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -58,7 +64,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (_collection[i] == null) { _collection[i] = obj; - return i; + return Count; } } return -1; @@ -108,4 +114,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects return null; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs index eabc5d7..8001079 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using ProjectMotorBoat.Drawings; using ProjectMotorBoat.MovementStrategy; +using System.Text; using System.Windows.Forms; namespace ProjectMotorBoat.CollectionGenericObjects; @@ -9,7 +10,7 @@ namespace ProjectMotorBoat.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawingBoat { /// /// Словарь (хранилище) с коллекциями @@ -21,6 +22,21 @@ public class StorageCollection /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -82,4 +98,145 @@ public class StorageCollection return null; } } + + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filename)) + { + File.Delete(filename); + } + + StringBuilder sb = new(); + + sb.Append(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + sb.Append(Environment.NewLine); + // Не сохраняем пустые коллекции + if (value.Value.Count == 0) + { + continue; + } + + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sb.Append(data); + sb.Append(_separatorItems); + } + } + + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) + { + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) + { + bufferTextFromFile += temp.GetString(b); + } + } + + string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + return false; + } + + if (!strs[0].Equals(_collectionKey)) + { + // Если нет такой записи, то это не те данные + return false; + } + + _storages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + continue; + } + + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + return false; + } + + collection.MaxCount = Convert.ToInt32(record[2]); + + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawingBoat() is T boat) + { + if (collection.Insert(boat) == 0) + { + return false; + } + } + } + + _storages.Add(record[0], collection); + } + + return true; + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } diff --git a/ProjectMotorBoat/ProjectMotorBoat/Drawings/DrawingBoat.cs b/ProjectMotorBoat/ProjectMotorBoat/Drawings/DrawingBoat.cs index 6d91165..76981e8 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/Drawings/DrawingBoat.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/Drawings/DrawingBoat.cs @@ -84,6 +84,13 @@ public class DrawingBoat EntityBoat = new EntityBoat(speed, weight, bodyColor); } + public DrawingBoat(EntityBoat entityBoat) + { + EntityBoat = entityBoat; + } + + + /// /// Конструктор для наследников /// diff --git a/ProjectMotorBoat/ProjectMotorBoat/Drawings/DrawingMotorBoat.cs b/ProjectMotorBoat/ProjectMotorBoat/Drawings/DrawingMotorBoat.cs index f939b5f..b4d7838 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/Drawings/DrawingMotorBoat.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/Drawings/DrawingMotorBoat.cs @@ -23,6 +23,11 @@ public class DrawingMotorBoat : DrawingBoat EntityBoat = new EntityMotorBoat(speed, weight, bodyColor, additionalColor, inboardEngine, oar, protectiveGlass); } + public DrawingMotorBoat(EntityBoat entityBoat) : base(100, 50) + { + EntityBoat = entityBoat; + } + /// /// Прорисовка объекта /// diff --git a/ProjectMotorBoat/ProjectMotorBoat/Drawings/ExtentionDrawingBoat.cs b/ProjectMotorBoat/ProjectMotorBoat/Drawings/ExtentionDrawingBoat.cs new file mode 100644 index 0000000..04c757d --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/Drawings/ExtentionDrawingBoat.cs @@ -0,0 +1,56 @@ +using ProjectMotorBoat.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMotorBoat.Drawings; + +/// +/// Расширение для класса EntityBoat +/// +public static class ExtentionDrawingBoat +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawingBoat? CreateDrawingBoat(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityBoat? boat = EntityMotorBoat.CreateEntityMotorBoat(strs); + + if (boat != null) + //return new DrawingMotorBoat(1,2,Color.Black,Color.Black,true,true,true); + return new DrawingMotorBoat(boat); + + boat = EntityBoat.CreateEntityBoat(strs); + if (boat != null) + //return new DrawingBoat(1, 2, Color.Black); + return new DrawingBoat(boat); + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawingBoat drawingBoat) + { + string[]? array = drawingBoat?.EntityBoat?.GetStringRepresentation(); + + if (array == null) + return string.Empty; + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectMotorBoat/ProjectMotorBoat/Entities/EntityBoat.cs b/ProjectMotorBoat/ProjectMotorBoat/Entities/EntityBoat.cs index d98c381..3aff601 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/Entities/EntityBoat.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/Entities/EntityBoat.cs @@ -44,4 +44,34 @@ public class EntityBoat { BodyColor = name; } + + /// + /// Поолучение строк с значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] + { + nameof(EntityBoat), + Speed.ToString(), + Weight.ToString(), + BodyColor.Name + }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityBoat? CreateEntityBoat(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityBoat)) + { + return null; + } + + return new EntityBoat(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectMotorBoat/ProjectMotorBoat/Entities/EntityMotorBoat.cs b/ProjectMotorBoat/ProjectMotorBoat/Entities/EntityMotorBoat.cs index 5489678..6551861 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/Entities/EntityMotorBoat.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/Entities/EntityMotorBoat.cs @@ -48,4 +48,44 @@ public class EntityMotorBoat : EntityBoat { AdditionalColor = name; } + + /// + /// Поолучение строк с значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] + { + nameof(EntityMotorBoat), + Speed.ToString(), + Weight.ToString(), + BodyColor.Name,AdditionalColor.Name, + InboardEngine.ToString(), + Oar.ToString(), + ProtectiveGlass.ToString() + }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityMotorBoat? CreateEntityMotorBoat(string[] strs) + { + if (strs.Length != 8 || strs[0] != nameof(EntityMotorBoat)) + { + return null; + } + + return new EntityMotorBoat( + Convert.ToInt32(strs[1]), + Convert.ToDouble(strs[2]), + Color.FromName(strs[3]), + Color.FromName(strs[4]), + Convert.ToBoolean(strs[5]), + Convert.ToBoolean(strs[6]), + Convert.ToBoolean(strs[7])); + } } \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs index 1cf8d06..fcf7995 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs @@ -46,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -59,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(777, 0); + groupBoxTools.Location = new Point(777, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(201, 585); + groupBoxTools.Size = new Size(201, 561); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -77,13 +84,13 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 329); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(195, 253); + panelCompanyTools.Size = new Size(195, 229); panelCompanyTools.TabIndex = 8; // // buttonAddBoat // buttonAddBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddBoat.Location = new Point(3, 3); + buttonAddBoat.Location = new Point(3, 4); buttonAddBoat.Name = "buttonAddBoat"; buttonAddBoat.Size = new Size(184, 32); buttonAddBoat.TabIndex = 1; @@ -94,7 +101,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 184); + buttonRefresh.Location = new Point(3, 177); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(184, 32); buttonRefresh.TabIndex = 6; @@ -104,7 +111,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(3, 79); + maskedTextBoxPosition.Location = new Point(3, 72); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(189, 23); @@ -114,7 +121,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 146); + buttonGoToCheck.Location = new Point(3, 139); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(184, 32); buttonGoToCheck.TabIndex = 5; @@ -125,7 +132,7 @@ // buttonRemoveBoat // buttonRemoveBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveBoat.Location = new Point(3, 108); + buttonRemoveBoat.Location = new Point(3, 101); buttonRemoveBoat.Name = "buttonRemoveBoat"; buttonRemoveBoat.Size = new Size(184, 32); buttonRemoveBoat.TabIndex = 4; @@ -240,12 +247,52 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(777, 585); + pictureBox.Size = new Size(777, 561); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(978, 24); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(48, 20); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(181, 22); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(181, 22); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormBoatCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -253,6 +300,8 @@ ClientSize = new Size(978, 585); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBoatCollection"; Text = " Коллекция лодок"; groupBoxTools.ResumeLayout(false); @@ -261,7 +310,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -284,5 +336,11 @@ private Label labelCollectionName; private Button buttonCreateCompany; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; } } \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs index 22684bd..a830c41 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs @@ -247,4 +247,46 @@ public partial class FormBoatCollection : Form panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + /// + /// Обработка нажатия "Загрузка" + /// + /// + /// + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + { + // TODO продумать логику + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.resx b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.resx index af32865..8b1dfa1 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.resx +++ b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 261, 17 + \ No newline at end of file -- 2.25.1 From b549f626a632b80b86f7cdbc31a2d3de30351296 Mon Sep 17 00:00:00 2001 From: easynickname1 <7326033@gmail.com> Date: Tue, 21 May 2024 00:48:53 +0400 Subject: [PATCH 2/8] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=967?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 12 ++- .../BoatHarborService.cs | 21 ++-- .../ICollectionGenericObjects.cs | 6 +- .../ListGenericObjects.cs | 47 ++++---- .../MassiveGenericObjects.cs | 47 ++++---- .../StorageCollection.cs | 39 ++++--- .../Exceptions/CollectionOverflowException.cs | 20 ++++ .../Exceptions/ObjectNotFoundException.cs | 20 ++++ .../PositionOutOfCollectionException.cs | 20 ++++ .../FormBoatCollection.Designer.cs | 16 +-- .../ProjectMotorBoat/FormBoatCollection.cs | 102 ++++++++++++------ ProjectMotorBoat/ProjectMotorBoat/Program.cs | 29 ++++- .../ProjectMotorBoat/ProjectMotorBoat.csproj | 12 +++ ProjectMotorBoat/ProjectMotorBoat/nlog.config | 15 +++ ProjectMotorBoat/ProjectMotorBoat/save.txt | 2 + ProjectMotorBoat/ProjectMotorBoat/save2.txt | 2 + 16 files changed, 283 insertions(+), 127 deletions(-) create mode 100644 ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectMotorBoat/ProjectMotorBoat/nlog.config create mode 100644 ProjectMotorBoat/ProjectMotorBoat/save.txt create mode 100644 ProjectMotorBoat/ProjectMotorBoat/save2.txt diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs index 5a87d1f..524d736 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs @@ -10,7 +10,7 @@ public abstract class AbstractCompany /// /// Размер места (ширина) /// - protected readonly int _placeSizeWidth = 120; + protected readonly int _placeSizeWidth = 126; /// /// Размер места (высота) @@ -35,7 +35,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth * _pictureHeight) / (_placeSizeWidth * _placeSizeHeight); /// /// Конструктор @@ -96,8 +96,12 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawingBoat? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawingBoat? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (Exception) { } } return bitmap; diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs index 0854001..58ee77b 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs @@ -1,5 +1,6 @@ using ProjectMotorBoat.Drawings; using ProjectMotorBoat.Entities; +using ProjectMotorBoat.Exceptions; using System.Drawing; namespace ProjectMotorBoat.CollectionGenericObjects; @@ -24,9 +25,9 @@ public class BoatHarborService : AbstractCompany { Pen pen = new(Color.BurlyWood, 4); - for (int startPosX = 5; (startPosX + _placeSizeWidth) < _pictureWidth; startPosX += _placeSizeWidth) + for (int startPosX = 0; (startPosX + _placeSizeWidth) < _pictureWidth; startPosX += _placeSizeWidth) { - for (int startPosY = 5; (startPosY + _placeSizeHeight) < _pictureHeight; startPosY += _placeSizeHeight) + for (int startPosY = 0; (startPosY + _placeSizeHeight) < _pictureHeight; startPosY += _placeSizeHeight) { Point[] points = { @@ -42,19 +43,23 @@ public class BoatHarborService : AbstractCompany protected override void SetObjectsPosition() { - int startPosX = 10; - int startPosY = 10; + int startPosX = 5; + int startPosY = 5; - for (int i = 0; _collection?.Get(i) != null; i++) + for (int i = 0; i < (_collection?.Count ?? 0); i++) { if (startPosX + _placeSizeWidth > _pictureWidth) { - startPosX = 10; + startPosX = 5; startPosY += _placeSizeHeight; } - _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i).SetPosition(startPosX, startPosY); + try + { + _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); + _collection.Get(i).SetPosition(startPosX, startPosY); + } + catch (Exception) { } startPosX += _placeSizeWidth; } diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs index b405892..329018d 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,7 +21,7 @@ public interface ICollectionGenericObjects /// Добавление объекта в коллекцию /// /// Добавляемый объект - /// true - вставка прошла удачно, false - вставка не удалась + /// Count - вставка прошла удачно, -1 - вставка не удалась int Insert(T obj); /// @@ -29,14 +29,14 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// Позиция - /// true - вставка прошла удачно, false - вставка не удалась + /// Count - вставка прошла удачно, -1 - вставка не удалась int Insert(T obj, int position); /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция - /// true - удаление прошло удачно, false - удаление не удалось + /// Объект T? Remove(int position); /// diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs index f815ab9..ff3e277 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectMotorBoat.CollectionGenericObjects; +using ProjectMotorBoat.Exceptions; + +namespace ProjectMotorBoat.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -39,46 +41,41 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < Count && _collection[position] != null) - { - return _collection[position]; - } - return null; + // выброс ошибки, если выход за границы массива + if (position < 0 || position > _collection.Count) throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { - if (Count < _maxCount) - { - _collection.Add(obj); - return _collection.Count; - } - return -1; + // выброс ошибки, если переполнение + if (Count >= _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); + return _collection.Count; } public int Insert(T obj, int position) { - if (Count < _maxCount) + // выброс ошибки, если переполнение + if (Count >= _maxCount) throw new CollectionOverflowException(); + + if (_collection[position] == null) { - if (_collection[position] == null) - { - _collection.Insert(position, obj); - return position; - } + _collection.Insert(position, obj); + return position; } return -1; } public T? Remove(int position) { - if (Count < _maxCount) + // выброс ошибки, если выход за границы массива + if (position < 0 || position > _collection.Count) throw new PositionOutOfCollectionException(position); + if (_collection[position] != null) { - if (_collection[position] != null) - { - T? obj = _collection[position]; - _collection.RemoveAt(position); - return obj; - } + T? obj = _collection[position]; + _collection.RemoveAt(position); + return obj; } return null; } diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs index 27cc790..a0ca361 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectMotorBoat.CollectionGenericObjects; +using ProjectMotorBoat.Exceptions; + +namespace ProjectMotorBoat.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -48,12 +50,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - // проверка позиции ✔ - if (_collection[position] != null && position < Count - 1) - { - return _collection[position]; - } - return null; + // выброс ошибки, если выход за границы массива + if (position >= Count) throw new PositionOutOfCollectionException(position); + // выброс ошибки, если объект пустой + if (_collection[position] == null) throw new ObjectNotFoundException(position); + + return _collection[position]; } public int Insert(T obj) @@ -67,16 +69,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects return Count; } } - return -1; + // выброс ошибки, если переполнение + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - // проверка позиции ✔ - // проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до ✔ - // вставка ✔ + // выброс ошибки, если выход за границы массива + if (position >= Count) throw new PositionOutOfCollectionException(position); + if (_collection[position] != null) { for (int i = position; i < Count; i++) @@ -97,22 +98,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } - - return -1; + // выброс ошибки, если переполнение + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - // проверка позиции ✔ - // удаление объекта из массива, присвоив элементу массива значение null ✔ - if (_collection[position] != null) - { - T? obj = _collection[position]; - _collection[position] = null; - return obj; - } + // выброс ошибки, если выход за границы массива + if (position >= Count) throw new PositionOutOfCollectionException(position); + // выброс ошибки, если объект пустой + if (_collection[position] == null) throw new ObjectNotFoundException(position); - return null; + T? obj = _collection[position]; + _collection[position] = null; + return obj; } public IEnumerable GetItems() diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs index 8001079..2c0555f 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectMotorBoat.Drawings; +using ProjectMotorBoat.Exceptions; using ProjectMotorBoat.MovementStrategy; using System.Text; using System.Windows.Forms; @@ -103,12 +104,11 @@ public class StorageCollection /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -151,19 +151,17 @@ public class StorageCollection using FileStream fs = new(filename, FileMode.Create); byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); fs.Write(info, 0, info.Length); - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } string bufferTextFromFile = ""; @@ -180,13 +178,12 @@ public class StorageCollection string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!strs[0].Equals(_collectionKey)) { - // Если нет такой записи, то это не те данные - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); @@ -199,12 +196,8 @@ public class StorageCollection } CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - return false; - } - + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -212,17 +205,21 @@ public class StorageCollection { if (elem?.CreateDrawingBoat() is T boat) { - if (collection.Insert(boat) == 0) + try { - return false; + if (collection.Insert(boat) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } - _storages.Add(record[0], collection); } - - return true; } /// diff --git a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..25aa59b --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectMotorBoat.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + + public CollectionOverflowException() : base() { } + + public CollectionOverflowException(string message) : base(message) { } + + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..d4bdf6d --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectMotorBoat.Exceptions; + +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + + public ObjectNotFoundException() : base() { } + + public ObjectNotFoundException(string message) : base(message) { } + + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..7bbfa51 --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectMotorBoat.Exceptions; + +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + + public PositionOutOfCollectionException() : base() { } + + public PositionOutOfCollectionException(string message) : base(message) { } + + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs index fcf7995..f6297f9 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs @@ -66,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(777, 24); + groupBoxTools.Location = new Point(763, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(201, 561); + groupBoxTools.Size = new Size(201, 544); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -82,15 +82,15 @@ panelCompanyTools.Controls.Add(buttonRemoveBoat); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 329); + panelCompanyTools.Location = new Point(3, 322); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(195, 229); + panelCompanyTools.Size = new Size(195, 219); panelCompanyTools.TabIndex = 8; // // buttonAddBoat // buttonAddBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddBoat.Location = new Point(3, 4); + buttonAddBoat.Location = new Point(3, 3); buttonAddBoat.Name = "buttonAddBoat"; buttonAddBoat.Size = new Size(184, 32); buttonAddBoat.TabIndex = 1; @@ -249,7 +249,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(777, 561); + pictureBox.Size = new Size(763, 544); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -258,7 +258,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(978, 24); + menuStrip.Size = new Size(964, 24); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip1"; // @@ -297,7 +297,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(978, 585); + ClientSize = new Size(964, 568); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); diff --git a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs index a830c41..525a334 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs @@ -1,4 +1,5 @@ -using ProjectMotorBoat.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectMotorBoat.CollectionGenericObjects; using ProjectMotorBoat.Drawings; namespace ProjectMotorBoat; @@ -18,13 +19,19 @@ public partial class FormBoatCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormBoatCollection() + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -61,14 +68,19 @@ public partial class FormBoatCollection : Form return; } - if (_company + boat >= 0) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + boat >= 0) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект: {boat}", boat.GetDataForSave()); + pictureBox.Image = _company.Show(); + } } - else + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -90,14 +102,20 @@ public partial class FormBoatCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation("Удалён объект по позиции: {pos}", pos); + pictureBox.Image = _company.Show(); + } } - else + catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -115,26 +133,33 @@ public partial class FormBoatCollection : Form DrawingBoat? boat = null; int counter = 100; - while (boat == null) + try { - boat = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (boat == null) { - break; + boat = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } - } - if (boat == null) - { - return; - } + if (boat == null) + { + return; + } - FormMotorBoat form = new() + FormMotorBoat form = new() + { + SetBoat = boat + }; + form.ShowDialog(); + } + catch (Exception ex) { - SetBoat = boat - }; - form.ShowDialog(); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// @@ -176,6 +201,7 @@ public partial class FormBoatCollection : Form } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавлена коллекция: {collection} Типа: {type}", textBoxCollectionName.Text, collectionType.ToString()); RerfreshListBoxItems(); } @@ -195,8 +221,11 @@ public partial class FormBoatCollection : Form return; } if (_storageCollection.Keys.Contains(listBoxCollection.SelectedItem.ToString() ?? string.Empty)) + { _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString() ?? string.Empty); + } + _logger.LogInformation("Удалена коллекция: {collection}", listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); } @@ -241,6 +270,7 @@ public partial class FormBoatCollection : Form { case "Хранилище": _company = new BoatHarborService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Создана компания на коллекции: {collection}", listBoxCollection.SelectedItem.ToString()); break; } @@ -257,13 +287,16 @@ public partial class FormBoatCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -275,18 +308,21 @@ public partial class FormBoatCollection : Form /// private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { - // TODO продумать логику if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); RerfreshListBoxItems(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } + } } } diff --git a/ProjectMotorBoat/ProjectMotorBoat/Program.cs b/ProjectMotorBoat/ProjectMotorBoat/Program.cs index bcbd11e..843a24c 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/Program.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectMotorBoat { internal static class Program @@ -11,7 +15,30 @@ namespace ProjectMotorBoat // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormBoatCollection()); + + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .WriteTo.File("boatlog-.log", rollingInterval: RollingInterval.Day) + .CreateLogger(); + + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// + /// Конфигурация сервиса DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(Log.Logger); + }); } } } \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj b/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj index 13ee123..659ff05 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj +++ b/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj @@ -8,6 +8,12 @@ enable + + + + + + True @@ -23,4 +29,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/nlog.config b/ProjectMotorBoat/ProjectMotorBoat/nlog.config new file mode 100644 index 0000000..d94f71a --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/save.txt b/ProjectMotorBoat/ProjectMotorBoat/save.txt new file mode 100644 index 0000000..36db68b --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/save.txt @@ -0,0 +1,2 @@ +CollectionsStorage +Коллекция|Massive|60|EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White; \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/save2.txt b/ProjectMotorBoat/ProjectMotorBoat/save2.txt new file mode 100644 index 0000000..458d81f --- /dev/null +++ b/ProjectMotorBoat/ProjectMotorBoat/save2.txt @@ -0,0 +1,2 @@ +CollectionsStorage +1|Massive|55|EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True; \ No newline at end of file -- 2.25.1 From bcf72b173ef6d7082b4046e9e8dc1867020e4724 Mon Sep 17 00:00:00 2001 From: easynickname1 <7326033@gmail.com> Date: Tue, 21 May 2024 00:52:52 +0400 Subject: [PATCH 3/8] =?UTF-8?q?=D0=A3=D0=B1=D1=80=D0=B0=D0=BD=20=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D1=83=D0=B6=D0=BD=D1=8B=D0=B9=20=D1=81=D0=B5=D0=B9?= =?UTF-8?q?=D0=B2=20=D0=B8=20=D0=BA=D0=BE=D0=BD=D1=84=D0=B8=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectMotorBoat/ProjectMotorBoat.csproj | 10 ++++------ ProjectMotorBoat/ProjectMotorBoat/nlog.config | 15 --------------- ProjectMotorBoat/ProjectMotorBoat/save2.txt | 2 -- 3 files changed, 4 insertions(+), 23 deletions(-) delete mode 100644 ProjectMotorBoat/ProjectMotorBoat/nlog.config delete mode 100644 ProjectMotorBoat/ProjectMotorBoat/save2.txt diff --git a/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj b/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj index 659ff05..fda71c6 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj +++ b/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj @@ -8,6 +8,10 @@ enable + + + + @@ -29,10 +33,4 @@ - - - Always - - - \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/nlog.config b/ProjectMotorBoat/ProjectMotorBoat/nlog.config deleted file mode 100644 index d94f71a..0000000 --- a/ProjectMotorBoat/ProjectMotorBoat/nlog.config +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/save2.txt b/ProjectMotorBoat/ProjectMotorBoat/save2.txt deleted file mode 100644 index 458d81f..0000000 --- a/ProjectMotorBoat/ProjectMotorBoat/save2.txt +++ /dev/null @@ -1,2 +0,0 @@ -CollectionsStorage -1|Massive|55|EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True;EntityMotorBoat:100:100:Yellow:Pink:False:True:True; \ No newline at end of file -- 2.25.1 From 01275ea1dd16833d07b00b74a66d1d8a0ea8e09b Mon Sep 17 00:00:00 2001 From: easynickname1 <7326033@gmail.com> Date: Sun, 26 May 2024 21:09:44 +0400 Subject: [PATCH 4/8] =?UTF-8?q?=D0=94=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD?= =?UTF-8?q?=D1=8B=20=D1=82=D1=80=D0=B5=D0=B1=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=B8=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D1=8B=20?= =?UTF-8?q?=D0=BD=D0=B5=D0=BD=D1=83=D0=B6=D0=BD=D1=8B=D0=B5=20=D1=84=D0=B0?= =?UTF-8?q?=D0=B9=D0=BB=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StorageCollection.cs | 139 ++++++++---------- 1 file changed, 65 insertions(+), 74 deletions(-) diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs index 8001079..a99fec6 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -116,41 +116,40 @@ public class StorageCollection File.Delete(filename); } - StringBuilder sb = new(); - - sb.Append(_collectionKey); - foreach (KeyValuePair> value in _storages) + using (StreamWriter wr = new StreamWriter(filename)) { - sb.Append(Environment.NewLine); - // Не сохраняем пустые коллекции - if (value.Value.Count == 0) + wr.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - continue; - } - - sb.Append(value.Key); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); - sb.Append(_separatorForKeyValue); - - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) + StringBuilder sb = new StringBuilder(); + sb.Append(Environment.NewLine); + // Не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } - sb.Append(data); - sb.Append(_separatorItems); + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sb.Append(data); + sb.Append(_separatorItems); + } + wr.Write(sb); } } - - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); return true; } @@ -166,62 +165,54 @@ public class StorageCollection return false; } - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader sr = new StreamReader(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) - { - bufferTextFromFile += temp.GetString(b); - } - } - - string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - return false; - } - - if (!strs[0].Equals(_collectionKey)) - { - // Если нет такой записи, то это не те данные - return false; - } - - _storages.Clear(); - foreach (string data in strs) - { - string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) - { - continue; - } - - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) + string str = sr.ReadLine(); + if (str == null || str.Length == 0) { return false; } - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + if (!str.Equals(_collectionKey)) { - if (elem?.CreateDrawingBoat() is T boat) - { - if (collection.Insert(boat) == 0) - { - return false; - } - } + // Если нет такой записи, то это не те данные + return false; } - _storages.Add(record[0], collection); - } + _storages.Clear(); + string data = ""; + while ((data = sr.ReadLine()) != null) + { + string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + continue; + } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + return false; + } + + collection.MaxCount = Convert.ToInt32(record[2]); + + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawingBoat() is T boat) + { + if (collection.Insert(boat) == 0) + { + return false; + } + } + } + + _storages.Add(record[0], collection); + } + } return true; } -- 2.25.1 From 595f6a9dbcf642176742aa908261c704b0e21de6 Mon Sep 17 00:00:00 2001 From: easynickname1 <7326033@gmail.com> Date: Sun, 26 May 2024 21:09:44 +0400 Subject: [PATCH 5/8] =?UTF-8?q?=D0=94=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD?= =?UTF-8?q?=D1=8B=20=D1=82=D1=80=D0=B5=D0=B1=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=B8=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D1=8B=20?= =?UTF-8?q?=D0=BD=D0=B5=D0=BD=D1=83=D0=B6=D0=BD=D1=8B=D0=B5=20=D1=84=D0=B0?= =?UTF-8?q?=D0=B9=D0=BB=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StorageCollection.cs | 132 ++++++++---------- 1 file changed, 62 insertions(+), 70 deletions(-) diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs index 2c0555f..b0d3ff6 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -116,41 +116,40 @@ public class StorageCollection File.Delete(filename); } - StringBuilder sb = new(); - - sb.Append(_collectionKey); - foreach (KeyValuePair> value in _storages) + using (StreamWriter wr = new StreamWriter(filename)) { - sb.Append(Environment.NewLine); - // Не сохраняем пустые коллекции - if (value.Value.Count == 0) + wr.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - continue; - } - - sb.Append(value.Key); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); - sb.Append(_separatorForKeyValue); - - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) + StringBuilder sb = new StringBuilder(); + sb.Append(Environment.NewLine); + // Не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } - sb.Append(data); - sb.Append(_separatorItems); + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sb.Append(data); + sb.Append(_separatorItems); + } + wr.Write(sb); } } - - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); } /// @@ -164,61 +163,54 @@ public class StorageCollection throw new Exception("Файл не существует"); } - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader sr = new StreamReader(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) + string str = sr.ReadLine(); + if (str == null || str.Length == 0) { - bufferTextFromFile += temp.GetString(b); - } - } - - string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - throw new Exception("В файле нет данных"); - } - - if (!strs[0].Equals(_collectionKey)) - { - throw new Exception("В файле неверные данные"); - } - - _storages.Clear(); - foreach (string data in strs) - { - string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) - { - continue; + throw new Exception("В файле нет данных"); } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? - throw new Exception("Не удалось определить тип коллекции:" + record[1]); - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + if (!str.Equals(_collectionKey)) { - if (elem?.CreateDrawingBoat() is T boat) + throw new Exception("В файле неверные данные"); + } + + _storages.Clear(); + string data = ""; + while ((data = sr.ReadLine()) != null) + { + string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) { - try + continue; + } + + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[2]); + + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawingBoat() is T boat) { - if (collection.Insert(boat) == -1) + try { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + if (collection.Insert(boat) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } - catch (CollectionOverflowException ex) - { - throw new Exception("Коллекция переполнена", ex); - } + _storages.Add(record[0], collection); } } - _storages.Add(record[0], collection); } } -- 2.25.1 From 88b25bd0d47de3b6812dd1264176ff996cc9cb42 Mon Sep 17 00:00:00 2001 From: easynickname1 <7326033@gmail.com> Date: Sun, 26 May 2024 21:41:55 +0400 Subject: [PATCH 6/8] =?UTF-8?q?Revert=20"=D0=94=D0=BE=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D0=B0=D0=BD=D1=8B=20=D1=82=D1=80=D0=B5=D0=B1=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D0=B8=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D1=8B=20=D0=BD=D0=B5=D0=BD=D1=83=D0=B6=D0=BD=D1=8B=D0=B5?= =?UTF-8?q?=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit fe943481a9c1f4f5d0a08fbd511856b5a145ffb1. --- .../StorageCollection.cs | 132 ++++++++++-------- 1 file changed, 70 insertions(+), 62 deletions(-) diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs index b0d3ff6..2c0555f 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -116,40 +116,41 @@ public class StorageCollection File.Delete(filename); } - using (StreamWriter wr = new StreamWriter(filename)) + StringBuilder sb = new(); + + sb.Append(_collectionKey); + foreach (KeyValuePair> value in _storages) { - wr.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + sb.Append(Environment.NewLine); + // Не сохраняем пустые коллекции + if (value.Value.Count == 0) { - StringBuilder sb = new StringBuilder(); - sb.Append(Environment.NewLine); - // Не сохраняем пустые коллекции - if (value.Value.Count == 0) + continue; + } + + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) { continue; } - sb.Append(value.Key); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); - sb.Append(_separatorForKeyValue); - - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) - { - continue; - } - - sb.Append(data); - sb.Append(_separatorItems); - } - wr.Write(sb); + sb.Append(data); + sb.Append(_separatorItems); } } + + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); } /// @@ -163,54 +164,61 @@ public class StorageCollection throw new Exception("Файл не существует"); } - using (StreamReader sr = new StreamReader(filename)) + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) { - string str = sr.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) { - throw new Exception("В файле нет данных"); + bufferTextFromFile += temp.GetString(b); + } + } + + string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + throw new Exception("В файле нет данных"); + } + + if (!strs[0].Equals(_collectionKey)) + { + throw new Exception("В файле неверные данные"); + } + + _storages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + continue; } - if (!str.Equals(_collectionKey)) + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[2]); + + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) { - throw new Exception("В файле неверные данные"); - } - - _storages.Clear(); - string data = ""; - while ((data = sr.ReadLine()) != null) - { - string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (elem?.CreateDrawingBoat() is T boat) { - continue; - } - - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? - throw new Exception("Не удалось определить тип коллекции:" + record[1]); - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) - { - if (elem?.CreateDrawingBoat() is T boat) + try { - try + if (collection.Insert(boat) == -1) { - if (collection.Insert(boat) == -1) - { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); - } - } - catch (CollectionOverflowException ex) - { - throw new Exception("Коллекция переполнена", ex); + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); } } - _storages.Add(record[0], collection); + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } } } + _storages.Add(record[0], collection); } } -- 2.25.1 From 8a3e041126ce48dba51abe9ef99cfceb0226e83f Mon Sep 17 00:00:00 2001 From: Pyro <732603@gmail.com> Date: Mon, 17 Jun 2024 00:15:50 +0400 Subject: [PATCH 7/8] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=966?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 12 +-- .../BoatHarborService.cs | 21 ++-- .../ICollectionGenericObjects.cs | 6 +- .../ListGenericObjects.cs | 47 ++++---- .../MassiveGenericObjects.cs | 47 ++++---- .../StorageCollection.cs | 50 +++++---- .../Exceptions/CollectionOverflowException.cs | 20 ---- .../Exceptions/ObjectNotFoundException.cs | 20 ---- .../PositionOutOfCollectionException.cs | 20 ---- .../FormBoatCollection.Designer.cs | 16 +-- .../ProjectMotorBoat/FormBoatCollection.cs | 102 ++++++------------ ProjectMotorBoat/ProjectMotorBoat/Program.cs | 29 +---- .../ProjectMotorBoat/ProjectMotorBoat.csproj | 10 -- ProjectMotorBoat/ProjectMotorBoat/save.txt | 2 - 14 files changed, 133 insertions(+), 269 deletions(-) delete mode 100644 ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs delete mode 100644 ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs delete mode 100644 ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs delete mode 100644 ProjectMotorBoat/ProjectMotorBoat/save.txt diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs index 524d736..5a87d1f 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/AbstractCompany.cs @@ -10,7 +10,7 @@ public abstract class AbstractCompany /// /// Размер места (ширина) /// - protected readonly int _placeSizeWidth = 126; + protected readonly int _placeSizeWidth = 120; /// /// Размер места (высота) @@ -35,7 +35,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => (_pictureWidth * _pictureHeight) / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); /// /// Конструктор @@ -96,12 +96,8 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - try - { - DrawingBoat? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); - } - catch (Exception) { } + DrawingBoat? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); } return bitmap; diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs index 58ee77b..0854001 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/BoatHarborService.cs @@ -1,6 +1,5 @@ using ProjectMotorBoat.Drawings; using ProjectMotorBoat.Entities; -using ProjectMotorBoat.Exceptions; using System.Drawing; namespace ProjectMotorBoat.CollectionGenericObjects; @@ -25,9 +24,9 @@ public class BoatHarborService : AbstractCompany { Pen pen = new(Color.BurlyWood, 4); - for (int startPosX = 0; (startPosX + _placeSizeWidth) < _pictureWidth; startPosX += _placeSizeWidth) + for (int startPosX = 5; (startPosX + _placeSizeWidth) < _pictureWidth; startPosX += _placeSizeWidth) { - for (int startPosY = 0; (startPosY + _placeSizeHeight) < _pictureHeight; startPosY += _placeSizeHeight) + for (int startPosY = 5; (startPosY + _placeSizeHeight) < _pictureHeight; startPosY += _placeSizeHeight) { Point[] points = { @@ -43,23 +42,19 @@ public class BoatHarborService : AbstractCompany protected override void SetObjectsPosition() { - int startPosX = 5; - int startPosY = 5; + int startPosX = 10; + int startPosY = 10; - for (int i = 0; i < (_collection?.Count ?? 0); i++) + for (int i = 0; _collection?.Get(i) != null; i++) { if (startPosX + _placeSizeWidth > _pictureWidth) { - startPosX = 5; + startPosX = 10; startPosY += _placeSizeHeight; } - try - { - _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i).SetPosition(startPosX, startPosY); - } - catch (Exception) { } + _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); + _collection.Get(i).SetPosition(startPosX, startPosY); startPosX += _placeSizeWidth; } diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs index 329018d..b405892 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,7 +21,7 @@ public interface ICollectionGenericObjects /// Добавление объекта в коллекцию /// /// Добавляемый объект - /// Count - вставка прошла удачно, -1 - вставка не удалась + /// true - вставка прошла удачно, false - вставка не удалась int Insert(T obj); /// @@ -29,14 +29,14 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// Позиция - /// Count - вставка прошла удачно, -1 - вставка не удалась + /// true - вставка прошла удачно, false - вставка не удалась int Insert(T obj, int position); /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция - /// Объект + /// true - удаление прошло удачно, false - удаление не удалось T? Remove(int position); /// diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs index ff3e277..f815ab9 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/ListGenericObjects.cs @@ -1,6 +1,4 @@ -using ProjectMotorBoat.Exceptions; - -namespace ProjectMotorBoat.CollectionGenericObjects; +namespace ProjectMotorBoat.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -41,41 +39,46 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - // выброс ошибки, если выход за границы массива - if (position < 0 || position > _collection.Count) throw new PositionOutOfCollectionException(position); - return _collection[position]; + if (position < Count && _collection[position] != null) + { + return _collection[position]; + } + return null; } public int Insert(T obj) { - // выброс ошибки, если переполнение - if (Count >= _maxCount) throw new CollectionOverflowException(Count); - _collection.Add(obj); - return _collection.Count; + if (Count < _maxCount) + { + _collection.Add(obj); + return _collection.Count; + } + return -1; } public int Insert(T obj, int position) { - // выброс ошибки, если переполнение - if (Count >= _maxCount) throw new CollectionOverflowException(); - - if (_collection[position] == null) + if (Count < _maxCount) { - _collection.Insert(position, obj); - return position; + if (_collection[position] == null) + { + _collection.Insert(position, obj); + return position; + } } return -1; } public T? Remove(int position) { - // выброс ошибки, если выход за границы массива - if (position < 0 || position > _collection.Count) throw new PositionOutOfCollectionException(position); - if (_collection[position] != null) + if (Count < _maxCount) { - T? obj = _collection[position]; - _collection.RemoveAt(position); - return obj; + if (_collection[position] != null) + { + T? obj = _collection[position]; + _collection.RemoveAt(position); + return obj; + } } return null; } diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs index a0ca361..27cc790 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,6 +1,4 @@ -using ProjectMotorBoat.Exceptions; - -namespace ProjectMotorBoat.CollectionGenericObjects; +namespace ProjectMotorBoat.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -50,12 +48,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - // выброс ошибки, если выход за границы массива - if (position >= Count) throw new PositionOutOfCollectionException(position); - // выброс ошибки, если объект пустой - if (_collection[position] == null) throw new ObjectNotFoundException(position); - - return _collection[position]; + // проверка позиции ✔ + if (_collection[position] != null && position < Count - 1) + { + return _collection[position]; + } + return null; } public int Insert(T obj) @@ -69,15 +67,16 @@ public class MassiveGenericObjects : ICollectionGenericObjects return Count; } } - // выброс ошибки, если переполнение - throw new CollectionOverflowException(Count); + return -1; } public int Insert(T obj, int position) { - // выброс ошибки, если выход за границы массива - if (position >= Count) throw new PositionOutOfCollectionException(position); - + // проверка позиции ✔ + // проверка, что элемент массива по этой позиции пустой, если нет, то + // ищется свободное место после этой позиции и идет вставка туда + // если нет после, ищем до ✔ + // вставка ✔ if (_collection[position] != null) { for (int i = position; i < Count; i++) @@ -98,20 +97,22 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } - // выброс ошибки, если переполнение - throw new CollectionOverflowException(Count); + + return -1; } public T? Remove(int position) { - // выброс ошибки, если выход за границы массива - if (position >= Count) throw new PositionOutOfCollectionException(position); - // выброс ошибки, если объект пустой - if (_collection[position] == null) throw new ObjectNotFoundException(position); + // проверка позиции ✔ + // удаление объекта из массива, присвоив элементу массива значение null ✔ + if (_collection[position] != null) + { + T? obj = _collection[position]; + _collection[position] = null; + return obj; + } - T? obj = _collection[position]; - _collection[position] = null; - return obj; + return null; } public IEnumerable GetItems() diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs index 58cdd3e..8555feb 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,4 @@ using ProjectMotorBoat.Drawings; -using ProjectMotorBoat.Exceptions; using ProjectMotorBoat.MovementStrategy; using System.Text; using System.Windows.Forms; @@ -108,7 +107,7 @@ public class StorageCollection { if (_storages.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + return false; } if (File.Exists(filename)) @@ -172,11 +171,16 @@ public class StorageCollection return false; } - if (!str.Equals(_collectionKey)) - { - // Если нет такой записи, то это не те данные - return false; - } + string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + throw new Exception("В файле нет данных"); + } + + if (!strs[0].Equals(_collectionKey)) + { + throw new Exception("В файле неверные данные"); + } _storages.Clear(); string data = ""; @@ -188,31 +192,31 @@ public class StorageCollection continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - return false; - } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[2]); - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawingBoat() is T boat) { - if (elem?.CreateDrawingBoat() is T boat) + try { - if (collection.Insert(boat) == 0) + if (collection.Insert(boat) == -1) { - return false; + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); } } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } } - - _storages.Add(record[0], collection); } + _storages.Add(record[0], collection); } - return true; } /// diff --git a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs deleted file mode 100644 index 25aa59b..0000000 --- a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/CollectionOverflowException.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Runtime.Serialization; - -namespace ProjectMotorBoat.Exceptions; - -/// -/// Класс, описывающий ошибку переполнения коллекции -/// -[Serializable] -internal class CollectionOverflowException : ApplicationException -{ - public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } - - public CollectionOverflowException() : base() { } - - public CollectionOverflowException(string message) : base(message) { } - - public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } - - protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } -} \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs deleted file mode 100644 index d4bdf6d..0000000 --- a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/ObjectNotFoundException.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Runtime.Serialization; - -namespace ProjectMotorBoat.Exceptions; - -/// -/// Класс, описывающий ошибку, что по указанной позиции нет элемента -/// -[Serializable] -internal class ObjectNotFoundException : ApplicationException -{ - public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } - - public ObjectNotFoundException() : base() { } - - public ObjectNotFoundException(string message) : base(message) { } - - public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } - - protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } -} \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs b/ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs deleted file mode 100644 index 7bbfa51..0000000 --- a/ProjectMotorBoat/ProjectMotorBoat/Exceptions/PositionOutOfCollectionException.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Runtime.Serialization; - -namespace ProjectMotorBoat.Exceptions; - -/// -/// Класс, описывающий ошибку выхода за границы коллекции -/// -[Serializable] -internal class PositionOutOfCollectionException : ApplicationException -{ - public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } - - public PositionOutOfCollectionException() : base() { } - - public PositionOutOfCollectionException(string message) : base(message) { } - - public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } - - protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } -} \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs index f6297f9..fcf7995 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.Designer.cs @@ -66,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(763, 24); + groupBoxTools.Location = new Point(777, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(201, 544); + groupBoxTools.Size = new Size(201, 561); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -82,15 +82,15 @@ panelCompanyTools.Controls.Add(buttonRemoveBoat); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 322); + panelCompanyTools.Location = new Point(3, 329); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(195, 219); + panelCompanyTools.Size = new Size(195, 229); panelCompanyTools.TabIndex = 8; // // buttonAddBoat // buttonAddBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddBoat.Location = new Point(3, 3); + buttonAddBoat.Location = new Point(3, 4); buttonAddBoat.Name = "buttonAddBoat"; buttonAddBoat.Size = new Size(184, 32); buttonAddBoat.TabIndex = 1; @@ -249,7 +249,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(763, 544); + pictureBox.Size = new Size(777, 561); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -258,7 +258,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(964, 24); + menuStrip.Size = new Size(978, 24); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip1"; // @@ -297,7 +297,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(964, 568); + ClientSize = new Size(978, 585); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); diff --git a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs index 525a334..a830c41 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/FormBoatCollection.cs @@ -1,5 +1,4 @@ -using Microsoft.Extensions.Logging; -using ProjectMotorBoat.CollectionGenericObjects; +using ProjectMotorBoat.CollectionGenericObjects; using ProjectMotorBoat.Drawings; namespace ProjectMotorBoat; @@ -19,19 +18,13 @@ public partial class FormBoatCollection : Form /// private AbstractCompany? _company = null; - /// - /// Логер - /// - private readonly ILogger _logger; - /// /// Конструктор /// - public FormBoatCollection(ILogger logger) + public FormBoatCollection() { InitializeComponent(); _storageCollection = new(); - _logger = logger; } /// @@ -68,19 +61,14 @@ public partial class FormBoatCollection : Form return; } - try + if (_company + boat >= 0) { - if (_company + boat >= 0) - { - MessageBox.Show("Объект добавлен"); - _logger.LogInformation("Добавлен объект: {boat}", boat.GetDataForSave()); - pictureBox.Image = _company.Show(); - } + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); } - catch (Exception ex) + else { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show("Не удалось добавить объект"); } } @@ -102,20 +90,14 @@ public partial class FormBoatCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - - try + if (_company - pos != null) { - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - _logger.LogInformation("Удалён объект по позиции: {pos}", pos); - pictureBox.Image = _company.Show(); - } + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); } - catch (Exception ex) + else { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show("Не удалось удалить объект"); } } @@ -133,33 +115,26 @@ public partial class FormBoatCollection : Form DrawingBoat? boat = null; int counter = 100; - try + while (boat == null) { - while (boat == null) + boat = _company.GetRandomObject(); + counter--; + if (counter <= 0) { - boat = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } + break; } - - if (boat == null) - { - return; - } - - FormMotorBoat form = new() - { - SetBoat = boat - }; - form.ShowDialog(); } - catch (Exception ex) + + if (boat == null) { - _logger.LogError("Ошибка: {Message}", ex.Message); + return; } + + FormMotorBoat form = new() + { + SetBoat = boat + }; + form.ShowDialog(); } /// @@ -201,7 +176,6 @@ public partial class FormBoatCollection : Form } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - _logger.LogInformation("Добавлена коллекция: {collection} Типа: {type}", textBoxCollectionName.Text, collectionType.ToString()); RerfreshListBoxItems(); } @@ -221,11 +195,8 @@ public partial class FormBoatCollection : Form return; } if (_storageCollection.Keys.Contains(listBoxCollection.SelectedItem.ToString() ?? string.Empty)) - { _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString() ?? string.Empty); - } - _logger.LogInformation("Удалена коллекция: {collection}", listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); } @@ -270,7 +241,6 @@ public partial class FormBoatCollection : Form { case "Хранилище": _company = new BoatHarborService(pictureBox.Width, pictureBox.Height, collection); - _logger.LogInformation("Создана компания на коллекции: {collection}", listBoxCollection.SelectedItem.ToString()); break; } @@ -287,16 +257,13 @@ public partial class FormBoatCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - try + if (_storageCollection.SaveData(saveFileDialog.FileName)) { - _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - catch (Exception ex) + else { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -308,21 +275,18 @@ public partial class FormBoatCollection : Form /// private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { + // TODO продумать логику if (openFileDialog.ShowDialog() == DialogResult.OK) { - try + if (_storageCollection.LoadData(openFileDialog.FileName)) { - _storageCollection.LoadData(openFileDialog.FileName); RerfreshListBoxItems(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - catch (Exception ex) + else { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - } } } diff --git a/ProjectMotorBoat/ProjectMotorBoat/Program.cs b/ProjectMotorBoat/ProjectMotorBoat/Program.cs index 843a24c..bcbd11e 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/Program.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/Program.cs @@ -1,7 +1,3 @@ -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Serilog; - namespace ProjectMotorBoat { internal static class Program @@ -15,30 +11,7 @@ namespace ProjectMotorBoat // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Information() - .WriteTo.File("boatlog-.log", rollingInterval: RollingInterval.Day) - .CreateLogger(); - - ServiceCollection services = new(); - ConfigureServices(services); - using ServiceProvider serviceProvider = services.BuildServiceProvider(); - Application.Run(serviceProvider.GetRequiredService()); - } - - /// - /// Конфигурация сервиса DI - /// - /// - private static void ConfigureServices(ServiceCollection services) - { - services.AddSingleton() - .AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddSerilog(Log.Logger); - }); + Application.Run(new FormBoatCollection()); } } } \ No newline at end of file diff --git a/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj b/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj index fda71c6..13ee123 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj +++ b/ProjectMotorBoat/ProjectMotorBoat/ProjectMotorBoat.csproj @@ -8,16 +8,6 @@ enable - - - - - - - - - - True diff --git a/ProjectMotorBoat/ProjectMotorBoat/save.txt b/ProjectMotorBoat/ProjectMotorBoat/save.txt deleted file mode 100644 index 36db68b..0000000 --- a/ProjectMotorBoat/ProjectMotorBoat/save.txt +++ /dev/null @@ -1,2 +0,0 @@ -CollectionsStorage -Коллекция|Massive|60|EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White;EntityBoat:100:100:White; \ No newline at end of file -- 2.25.1 From 847ecf21d8c1a78acb932955db36f20f8442b15d Mon Sep 17 00:00:00 2001 From: Pyro <732603@gmail.com> Date: Mon, 17 Jun 2024 00:34:43 +0400 Subject: [PATCH 8/8] fix --- .../StorageCollection.cs | 49 +++++++------------ 1 file changed, 18 insertions(+), 31 deletions(-) diff --git a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs index 8555feb..18ecd0e 100644 --- a/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorBoat/ProjectMotorBoat/CollectionGenericObjects/StorageCollection.cs @@ -54,7 +54,7 @@ public class StorageCollection { // проверка, что name не пустой и нет в словаре записи с таким ключом ✔ // Прописать логику для добавления ✔ - if (name != null && !_storages.ContainsKey(name)) + if (name != null && !_storages.ContainsKey(name)) { switch (collectionType) { @@ -103,7 +103,7 @@ public class StorageCollection /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла - public void SaveData(string filename) + public bool SaveData(string filename) { if (_storages.Count == 0) { @@ -156,11 +156,11 @@ public class StorageCollection /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла - public void LoadData(string filename) + public bool LoadData(string filename) { if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + return false; } using (StreamReader sr = new StreamReader(filename)) @@ -171,16 +171,10 @@ public class StorageCollection return false; } - string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - throw new Exception("В файле нет данных"); - } - - if (!strs[0].Equals(_collectionKey)) - { - throw new Exception("В файле неверные данные"); - } + if (!str[0].Equals(_collectionKey)) + { + return false; + } _storages.Clear(); string data = ""; @@ -192,30 +186,23 @@ public class StorageCollection continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? - throw new Exception("Не удалось определить тип коллекции:" + record[1]); - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) - { - if (elem?.CreateDrawingBoat() is T boat) + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + collection.MaxCount = Convert.ToInt32(record[2]); + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) { - try + if (elem?.CreateDrawingBoat() is T boat) { if (collection.Insert(boat) == -1) { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + return false; } } - catch (CollectionOverflowException ex) - { - throw new Exception("Коллекция переполнена", ex); - } } + _storages.Add(record[0], collection); } - _storages.Add(record[0], collection); + return true; } } @@ -233,4 +220,4 @@ public class StorageCollection _ => null, }; } -} +} \ No newline at end of file -- 2.25.1