From e61d3cb96a18daece40775ff54e904e71701ef89 Mon Sep 17 00:00:00 2001 From: insideq Date: Fri, 12 Apr 2024 20:25:19 +0400 Subject: [PATCH 1/2] =?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 | 17 +- .../MassiveGenericObjects.cs | 20 ++- .../StorageCollection.cs | 163 +++++++++++++++++- .../Drawnings/DrawningBulldozer.cs | 11 +- .../Drawnings/DrawningExcavator.cs | 9 + .../Drawnings/ExtentionDrawningBulldozer.cs | 54 ++++++ .../Entities/EntityBulldozer.cs | 24 +++ .../Entities/EntityExcavator.cs | 24 +++ .../FormBulldozerCollection.Designer.cs | 76 +++++++- .../FormBulldozerCollection.cs | 46 ++++- .../FormBulldozerCollection.resx | 9 + 13 files changed, 447 insertions(+), 21 deletions(-) create mode 100644 ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningBulldozer.cs diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs index 3772f55..da382ce 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectExcavator/ProjectExcavator/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/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs index af57cfc..eb0354e 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/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/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs index f136c26..8bb0c67 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectExcavator.CollectionGenericObjects; + +namespace ProjectExcavator.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects where T : class @@ -15,7 +16,9 @@ public class ListGenericObjects : ICollectionGenericObjects public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount { get { return _collection.Count; } set { if (value > 0) { _maxCount = value; } } } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -41,7 +44,7 @@ public class ListGenericObjects : ICollectionGenericObjects return -1; } // TODO вставка в конец набора - _collection.Insert(0, obj); + _collection.Add(obj); return 0; } @@ -69,4 +72,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection[position] = null; return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; i++) + { + yield return _collection[i]; + } + } } diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs index d8204e3..cf5d7bc 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectExcavator.CollectionGenericObjects; + +namespace ProjectExcavator.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -14,8 +15,13 @@ 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 +38,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -119,4 +127,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i< _collection.Length; i++) + { + yield return _collection[i]; + } + } } diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs index 8b2bda0..3f2d9c8 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,14 @@ -namespace ProjectExcavator.CollectionGenericObjects; +using ProjectExcavator.Drawnings; +using System.Text; + +namespace ProjectExcavator.CollectionGenericObjects; /// /// Класс - хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningBulldozer { /// /// Словарь (хранилище) с коллекциями @@ -16,6 +19,21 @@ public class StorageCollection /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; /// /// Конструктор @@ -76,4 +94,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?.CreateDrawningBulldozer() is T bulldozer) + { + if (collection.Insert(bulldozer) == - 1) + { + 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/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBulldozer.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBulldozer.cs index 7fa5983..1cae0b6 100644 --- a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBulldozer.cs +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBulldozer.cs @@ -65,7 +65,7 @@ public class DrawningBulldozer /// /// Пустой конструктор /// - private DrawningBulldozer() + public DrawningBulldozer() // было private { _pictureWidth = null; _pictureHeight = null; @@ -95,6 +95,15 @@ public class DrawningBulldozer _drawingExcHeight = drawingExcHeight; } + /// + /// Конструктор, принимающий объект EntityBulldozer в качестве параметра + /// + /// + public DrawningBulldozer(EntityBulldozer entityBulldozer) + { + EntityBulldozer = entityBulldozer; + } + /// /// Установка границ поля /// diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs index b3f3e6a..36a68b5 100644 --- a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs @@ -21,6 +21,15 @@ public class DrawningExcavator : DrawningBulldozer EntityBulldozer = new EntityExcavator(speed, weight, bodyColor, additionalColor, prop, ladle); } + /// + /// Конструктор, принимающий объект EntityBulldozer в качестве параметра + /// + /// + public DrawningExcavator(EntityBulldozer entityBulldozer) + { + EntityBulldozer = entityBulldozer; + } + public override void DrawTransport(Graphics g) { if (EntityBulldozer == null || EntityBulldozer is not EntityExcavator excavator || !_startPosX.HasValue || !_startPosX.HasValue) diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningBulldozer.cs b/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningBulldozer.cs new file mode 100644 index 0000000..77c4852 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningBulldozer.cs @@ -0,0 +1,54 @@ +using ProjectExcavator.Entities; + +namespace ProjectExcavator.Drawnings; + +/// +/// Расширение для класса EntityBulldozer +/// +public static class ExtentionDrawningBulldozer +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningBulldozer? CreateDrawningBulldozer(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityBulldozer? bulldozer = EntityExcavator.CreateEntityExcavator(strs); + if (bulldozer != null) + { + return new DrawningExcavator(bulldozer); + } + + bulldozer = EntityBulldozer.CreateEntityBulldozer(strs); + if (bulldozer != null) + { + return new DrawningBulldozer(bulldozer); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningBulldozer drawningBulldozer) + { + string[]? array = drawningBulldozer?.EntityBulldozer?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectExcavator/ProjectExcavator/Entities/EntityBulldozer.cs b/ProjectExcavator/ProjectExcavator/Entities/EntityBulldozer.cs index 3cc851d..9015d44 100644 --- a/ProjectExcavator/ProjectExcavator/Entities/EntityBulldozer.cs +++ b/ProjectExcavator/ProjectExcavator/Entities/EntityBulldozer.cs @@ -40,4 +40,28 @@ public class EntityBulldozer Weight = weight; BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityBulldozer), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityBulldozer? CreateEntityBulldozer(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityBulldozer)) + { + return null; + } + + return new EntityBulldozer(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectExcavator/ProjectExcavator/Entities/EntityExcavator.cs b/ProjectExcavator/ProjectExcavator/Entities/EntityExcavator.cs index e878ec4..3aed7ce 100644 --- a/ProjectExcavator/ProjectExcavator/Entities/EntityExcavator.cs +++ b/ProjectExcavator/ProjectExcavator/Entities/EntityExcavator.cs @@ -36,4 +36,28 @@ public class EntityExcavator : EntityBulldozer Prop = prop; Ladle = ladle; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityExcavator), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Prop.ToString(), Ladle.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityExcavator? CreateEntityExcavator(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityExcavator)) + { + return null; + } + + return new EntityExcavator(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } } diff --git a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.Designer.cs b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.Designer.cs index 145a2e1..243324f 100644 --- a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.Designer.cs +++ b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.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(774, 0); + groupBoxTools.Location = new Point(774, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(187, 600); + groupBoxTools.Size = new Size(187, 576); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -77,13 +84,13 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 328); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(181, 269); + panelCompanyTools.Size = new Size(181, 245); panelCompanyTools.TabIndex = 9; // // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(12, 177); + buttonGoToCheck.Location = new Point(12, 148); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(160, 42); buttonGoToCheck.TabIndex = 5; @@ -105,7 +112,7 @@ // buttonRemoveCar // buttonRemoveCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveCar.Location = new Point(12, 129); + buttonRemoveCar.Location = new Point(12, 100); buttonRemoveCar.Name = "buttonRemoveCar"; buttonRemoveCar.Size = new Size(160, 42); buttonRemoveCar.TabIndex = 4; @@ -115,7 +122,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(12, 100); + maskedTextBoxPosition.Location = new Point(12, 71); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(160, 23); @@ -125,7 +132,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(12, 225); + buttonRefresh.Location = new Point(12, 196); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(160, 42); buttonRefresh.TabIndex = 6; @@ -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(774, 600); + pictureBox.Size = new Size(774, 576); 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(961, 24); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // файл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"; + // // FormBulldozerCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -253,6 +300,8 @@ ClientSize = new Size(961, 600); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBulldozerCollection"; 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 Button buttonCreateCompany; private Button buttonCollectionDel; 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/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs index ba06339..7ce8fa1 100644 --- a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs +++ b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs @@ -152,7 +152,7 @@ public partial class FormBulldozerCollection : Form } CollectionType collectionType = CollectionType.None; - if(radioButtonMassive.Checked) + if (radioButtonMassive.Checked) { collectionType = CollectionType.Massive; } @@ -210,7 +210,7 @@ public partial class FormBulldozerCollection : Form for (int i = 0; i < _storageCollection.Keys?.Count; i++) { string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName) ) + if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); } @@ -247,4 +247,46 @@ public partial class FormBulldozerCollection : Form panelCompanyTools.Enabled = true; RefreshListBoxItems(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + + RefreshListBoxItems(); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.resx b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.resx index af32865..8b1dfa1 100644 --- a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.resx +++ b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.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 20d212bc57961d96ebffb6491f929e7a8fb35bf5 Mon Sep 17 00:00:00 2001 From: insideq Date: Thu, 25 Apr 2024 19:16:55 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=98=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BB=20StreamWriter=20=D0=B8=20StreamReader?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StorageCollection.cs | 136 ++++++++---------- .../Drawnings/DrawningBulldozer.cs | 5 +- .../Drawnings/DrawningExcavator.cs | 4 +- .../Drawnings/ExtentionDrawningBulldozer.cs | 2 +- 4 files changed, 69 insertions(+), 78 deletions(-) diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs index 3f2d9c8..8ad5434 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs @@ -112,41 +112,38 @@ public class StorageCollection File.Delete(filename); } - StringBuilder sb = new(); - - sb.Append(_collectionKey); - foreach (KeyValuePair> value in _storages) + using (StreamWriter writer = new StreamWriter(filename)) { - sb.Append(Environment.NewLine); - // не сохраняем пустые коллекции - if (value.Value.Count == 0) + writer.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)) + writer.Write(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } - sb.Append(data); - sb.Append(_separatorItems); + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.GetCollectionType); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + writer.Write(data); + writer.Write(_separatorItems); + } } } - - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); return true; } @@ -162,62 +159,55 @@ public class StorageCollection return false; } - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader reader = File.OpenText(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) - { - bufferTextFromFile += temp.GetString(b); - } - } + string str = reader.ReadLine(); - 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) + 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.StartsWith(_collectionKey)) { - if (elem?.CreateDrawningBulldozer() is T bulldozer) - { - if (collection.Insert(bulldozer) == - 1) - { - return false; - } - } + //если нет такой записи, то это не те данные + return false; } - _storages.Add(record[0], collection); - } + _storages.Clear(); + string strs = ""; + while ((strs = reader.ReadLine()) != null) + { + string[] record = strs.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?.CreateDrawningBulldozer() is T bulldozer) + { + if (collection.Insert(bulldozer) == -1) + { + return false; + } + } + } + + _storages.Add(record[0], collection); + } + } return true; } diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBulldozer.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBulldozer.cs index 1cae0b6..06e38da 100644 --- a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBulldozer.cs +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningBulldozer.cs @@ -1,4 +1,5 @@ using ProjectExcavator.Entities; +using System.Security.Policy; namespace ProjectExcavator.Drawnings; @@ -99,9 +100,9 @@ public class DrawningBulldozer /// Конструктор, принимающий объект EntityBulldozer в качестве параметра /// /// - public DrawningBulldozer(EntityBulldozer entityBulldozer) + public DrawningBulldozer(EntityBulldozer bull) : this() { - EntityBulldozer = entityBulldozer; + EntityBulldozer = new EntityBulldozer(bull.Speed, bull.Weight, bull.BodyColor); } /// diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs index 36a68b5..fd49b1e 100644 --- a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavator.cs @@ -25,9 +25,9 @@ public class DrawningExcavator : DrawningBulldozer /// Конструктор, принимающий объект EntityBulldozer в качестве параметра /// /// - public DrawningExcavator(EntityBulldozer entityBulldozer) + public DrawningExcavator(EntityExcavator exc) : base(150, 80) { - EntityBulldozer = entityBulldozer; + EntityBulldozer = new EntityExcavator(exc.Speed, exc.Weight, exc.BodyColor, exc.AdditionalColor, exc.Prop, exc.Ladle); } public override void DrawTransport(Graphics g) diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningBulldozer.cs b/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningBulldozer.cs index 77c4852..96f4dc0 100644 --- a/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningBulldozer.cs +++ b/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningBulldozer.cs @@ -23,7 +23,7 @@ public static class ExtentionDrawningBulldozer EntityBulldozer? bulldozer = EntityExcavator.CreateEntityExcavator(strs); if (bulldozer != null) { - return new DrawningExcavator(bulldozer); + return new DrawningExcavator((EntityExcavator)bulldozer); } bulldozer = EntityBulldozer.CreateEntityBulldozer(strs); -- 2.25.1