From a8bcb964fed487beca502420590633c9ffe0793f Mon Sep 17 00:00:00 2001 From: Ekaterina23578 Date: Tue, 7 May 2024 11:43:58 +0400 Subject: [PATCH 1/2] =?UTF-8?q?6=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 14 +- .../ListGenericObjects.cs | 12 +- .../MassiveGenericObjects.cs | 18 ++- .../StorageCollection.cs | 152 +++++++++++++++++- .../Drawnings/DrawningAirBomber.cs | 12 +- .../Drawnings/DrawningBomber.cs | 10 +- .../Drawnings/ExtentionDrawningBomber.cs | 61 +++++++ .../Entities/EntityAirBomber.cs | 22 +++ .../ProjectAirBomber/Entities/EntityBomber.cs | 25 +++ .../FormBomberCollection.Designer.cs | 74 +++++++-- .../ProjectAirBomber/FormBomberCollection.cs | 43 ++++- .../FormBomberCollection.resx | 9 ++ 13 files changed, 435 insertions(+), 19 deletions(-) create mode 100644 ProjectAirBomber/ProjectAirBomber/Drawnings/ExtentionDrawningBomber.cs diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs index 9dd23ca..d5072b4 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/AbstractCompany.cs @@ -55,7 +55,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs index 07b2576..4e9c2a0 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,7 +21,8 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } + /// /// Добавление объекта в коллекцию @@ -51,4 +52,15 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs index dac502d..26facf7 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/ListGenericObjects.cs @@ -25,7 +25,9 @@ public class ListGenericObjects : ICollectionGenericObjects public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -63,4 +65,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs index dd3fe2b..b45b604 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/MassiveGenericObjects.cs @@ -21,8 +21,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } + set { if (value > 0) @@ -37,8 +42,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } + } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// конструктор /// @@ -116,4 +124,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs index 052c085..60d3d8a 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using ProjectAirBomber.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -11,18 +12,32 @@ namespace ProjectAirBomber.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningBomber { /// /// Словарь (хранилище) с коллекциями /// readonly Dictionary> _storages; - /// /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -79,4 +94,135 @@ 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; + } + + using (StreamReader reader = File.OpenText(filename)) + { + string? str = reader.ReadLine(); + if (str == null || str.Length == 0) + { + return false; + } + if (!str.StartsWith(_collectionKey)) + { + return false; + } + _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?.CreateDrawningBomber() is T bomber) + { + if (collection.Insert(bomber) == -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, + }; + } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningAirBomber.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningAirBomber.cs index 95d887f..2e9a795 100644 --- a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningAirBomber.cs +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningAirBomber.cs @@ -16,11 +16,21 @@ public class DrawningAirBomber : DrawningBomber /// Дополнительный цвет /// Признак наличия бомб /// Признак наличия топливных баков - public DrawningAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(150, 145) + public DrawningAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(145, 148) { EntityBomber = new EntityAirBomber(speed, weight, bodyColor, additionalColor, bombs, fuelTanks); } + /// + /// Конструктор + /// + /// Класс-сущность + public DrawningAirBomber(EntityBomber bomber) : base(140, 90) + { + EntityBomber = bomber; + } + + public override void DrawTransport(Graphics g) { diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs index aee17ab..ba7c96e 100644 --- a/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/DrawningBomber.cs @@ -79,7 +79,6 @@ public class DrawningBomber _startPosY = null; } - /// /// Конструктор /// @@ -92,6 +91,15 @@ public class DrawningBomber EntityBomber = new EntityBomber(speed, weight, bodyColor); } + /// + /// Конструктор + /// + /// Класс-сущность + public DrawningBomber(EntityBomber bomber) : this() + { + EntityBomber = bomber; + } + /// /// Конструктор для наследников /// diff --git a/ProjectAirBomber/ProjectAirBomber/Drawnings/ExtentionDrawningBomber.cs b/ProjectAirBomber/ProjectAirBomber/Drawnings/ExtentionDrawningBomber.cs new file mode 100644 index 0000000..9bd9fa8 --- /dev/null +++ b/ProjectAirBomber/ProjectAirBomber/Drawnings/ExtentionDrawningBomber.cs @@ -0,0 +1,61 @@ +using ProjectAirBomber.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using static System.Runtime.InteropServices.JavaScript.JSType; + +namespace ProjectAirBomber.Drawnings; + +/// +/// Расширение для класса EntityBomber +/// +public static class ExtentionDrawningBomber +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningBomber? CreateDrawningBomber(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityBomber? bomber = EntityAirBomber.CreateEntityAirBomber(strs); + if (bomber != null) + { + return new DrawningAirBomber(bomber); + } + + bomber = EntityBomber.CreateEntityBomber(strs); + if (bomber != null) + { + return new DrawningBomber(bomber); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningBomber drawningBomber) + { + string[]? array = drawningBomber?.EntityBomber?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} + diff --git a/ProjectAirBomber/ProjectAirBomber/Entities/EntityAirBomber.cs b/ProjectAirBomber/ProjectAirBomber/Entities/EntityAirBomber.cs index beb0a8a..eb0090a 100644 --- a/ProjectAirBomber/ProjectAirBomber/Entities/EntityAirBomber.cs +++ b/ProjectAirBomber/ProjectAirBomber/Entities/EntityAirBomber.cs @@ -36,7 +36,29 @@ public class EntityAirBomber : EntityBomber /// public bool FuelTanks { get; private set; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityAirBomber), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Bombs.ToString(), FuelTanks.ToString() }; + } + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityAirBomber? CreateEntityAirBomber(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityAirBomber)) + { + return null; + } + return new EntityAirBomber(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/ProjectAirBomber/ProjectAirBomber/Entities/EntityBomber.cs b/ProjectAirBomber/ProjectAirBomber/Entities/EntityBomber.cs index cf7fb24..1dfb57a 100644 --- a/ProjectAirBomber/ProjectAirBomber/Entities/EntityBomber.cs +++ b/ProjectAirBomber/ProjectAirBomber/Entities/EntityBomber.cs @@ -56,4 +56,29 @@ public class EntityBomber BodyColor = bodyColor; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityBomber), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityBomber? CreateEntityBomber(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityBomber)) + { + return null; + } + + return new EntityBomber(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } + + diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs index 0a99673..ea67e6e 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.Designer.cs @@ -32,7 +32,6 @@ panelCompanyTools = new Panel(); maskedTextBox = new MaskedTextBox(); buttonAddBomber = new Button(); - buttonAddAirBomber = new Button(); buttonRefresh = new Button(); buttonDelBomber = new Button(); buttonGoToCheck = new Button(); @@ -47,11 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox1 = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + openFileDialog = new OpenFileDialog(); + saveFileDialog = new SaveFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); - panelCompanyTools.SuspendLayout(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -61,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(758, 0); + groupBoxTools.Location = new Point(758, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(251, 683); + groupBoxTools.Size = new Size(251, 655); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -72,7 +77,6 @@ // panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonAddBomber); - panelCompanyTools.Controls.Add(buttonAddAirBomber); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonDelBomber); panelCompanyTools.Controls.Add(buttonGoToCheck); @@ -95,7 +99,7 @@ // buttonAddBomber // buttonAddBomber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddBomber.Location = new Point(3, 4); + buttonAddBomber.Location = new Point(3, 3); buttonAddBomber.Name = "buttonAddBomber"; buttonAddBomber.Size = new Size(224, 51); buttonAddBomber.TabIndex = 1; @@ -243,12 +247,54 @@ // pictureBox1 // pictureBox1.Dock = DockStyle.Fill; - pictureBox1.Location = new Point(0, 0); + pictureBox1.Location = new Point(0, 28); pictureBox1.Name = "pictureBox1"; - pictureBox1.Size = new Size(758, 683); + pictureBox1.Size = new Size(758, 655); pictureBox1.TabIndex = 1; pictureBox1.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1009, 28); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(59, 24); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(227, 26); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(227, 26); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog"; + openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // // FormBomberCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -256,6 +302,8 @@ ClientSize = new Size(1009, 683); Controls.Add(pictureBox1); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBomberCollection"; Text = "Коллекция бомбардировщиков"; groupBoxTools.ResumeLayout(false); @@ -264,7 +312,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -272,7 +323,6 @@ private GroupBox groupBoxTools; private Button buttonAddBomber; private ComboBox comboBoxSelectorCompany; - private Button buttonAddAirBomber; private PictureBox pictureBox1; private Button buttonDelBomber; private MaskedTextBox maskedTextBox; @@ -288,5 +338,11 @@ private Button buttonCollectionDel; private Button buttonCreateCompany; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs index 7938c63..9f6a56a 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.cs @@ -295,7 +295,7 @@ public partial class FormBomberCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection [listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -312,5 +312,46 @@ public partial class FormBomberCollection : 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) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RerfreshListBoxItems(); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx index af32865..b7ad5cc 100644 --- a/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx +++ b/ProjectAirBomber/ProjectAirBomber/FormBomberCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 145, 17 + + + 315, 17 + \ No newline at end of file -- 2.25.1 From b4c1796f232290ec418215a155f4e89ecea0808f Mon Sep 17 00:00:00 2001 From: Ekaterina23578 Date: Sat, 11 May 2024 15:57:19 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=BD=D0=BE=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StorageCollection.cs | 98 +++++++++---------- 1 file changed, 46 insertions(+), 52 deletions(-) diff --git a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs index 60d3d8a..831909c 100644 --- a/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirBomber/ProjectAirBomber/CollectionGenericObjects/StorageCollection.cs @@ -96,7 +96,7 @@ public class StorageCollection } /// - /// Сохранение информации по автомобилям в хранилище в файл + /// Сохранение информации по бомбардировщикам в хранилище в файл /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных @@ -112,24 +112,23 @@ public class StorageCollection File.Delete(filename); } - StringBuilder sb = new(); - - sb.Append(_collectionKey); + using StreamWriter writer = new StreamWriter(filename); + writer.Write(_collectionKey); foreach (KeyValuePair> value in _storages) { - sb.Append(Environment.NewLine); + writer.Write(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); + 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()) { @@ -139,14 +138,11 @@ public class StorageCollection continue; } - sb.Append(data); - sb.Append(_separatorItems); + 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,53 +158,51 @@ public class StorageCollection return false; } - using (StreamReader reader = File.OpenText(filename)) + using StreamReader reader = File.OpenText(filename); + string? str = reader.ReadLine(); + if (str == null || str.Length == 0) { - string? str = reader.ReadLine(); - if (str == null || str.Length == 0) + return false; + } + if (!str.StartsWith(_collectionKey)) + { + return false; + } + _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; } - if (!str.StartsWith(_collectionKey)) + collection.MaxCount = Convert.ToInt32(record[2]); + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + + foreach (string elem in set) { - return false; - } - _storages.Clear(); - string? strs = ""; - - while ((strs = reader.ReadLine()) != null) - { - string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (elem?.CreateDrawningBomber() is T bomber) { - 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?.CreateDrawningBomber() is T bomber) + if (collection.Insert(bomber) == -1) { - if (collection.Insert(bomber) == -1) - { - return false; - } + return false; } } - _storages.Add(record[0], collection); } - - return true; + _storages.Add(record[0], collection); } + + return true; } /// -- 2.25.1