diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs index 39e9cdf..d4505ce 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs index 157a9d6..c09af86 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -14,7 +14,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int MaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию /// diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs index 560a689..340f979 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs @@ -11,9 +11,24 @@ public class ListGenericObjects : ICollectionGenericObjects /// Максимально допустимое число объектов в списке /// private int _maxCount; - public CollectionType GetCollectionType => CollectionType.List; + public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get + { + return Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор /// diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs index 405ec89..04e083d 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using SelfPropelledArtilleryUnit.Drawnings; +using System.Text; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; public class StorageCollection @@ -12,6 +13,22 @@ public class StorageCollection /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -61,5 +78,128 @@ 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); + } + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + StringBuilder sb = new(); + 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); + } + writer.Write(sb); + } + } + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + using (StreamReader fs = File.OpenText(filename)) + { + string str = fs.ReadLine(); + if (str == null || str.Length == 0) + { + return false; + } + if (!str.StartsWith(_collectionKey)) + { + return false; + } + _storages.Clear(); + string strs = ""; + while ((strs = fs.ReadLine()) != null) + { + //по идее этого произойти не должно + //if (strs == null) + //{ + // return false; + //} + 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?.CreateDrawningPropelledArtillery() is T ship) + { + if (collection.Insert(ship) == -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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/ExtentionDrawningPropelledArtillery.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/ExtentionDrawningPropelledArtillery.cs index 6feebc1..1e945df 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/ExtentionDrawningPropelledArtillery.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Drawnings/ExtentionDrawningPropelledArtillery.cs @@ -38,9 +38,9 @@ public static class ExtentionDrawningPropelledArtillery /// /// Сохраняемый объект /// Строка с данными по объекту - public static string GetDataForSave(this DrawningPropelledArtillery drawningCar) + public static string GetDataForSave(this DrawningPropelledArtillery drawningPropelledArtillery) { - string[]? array = drawningCar?.EntityPropelledArtillery?.GetStringRepresentation(); + string[]? array = drawningPropelledArtillery?.EntityPropelledArtillery?.GetStringRepresentation(); if (array == null) { return string.Empty; diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.Designer.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.Designer.cs index be3488d..9199c3d 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.Designer.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.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(736, 0); + groupBoxTools.Location = new Point(736, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(200, 562); + groupBoxTools.Size = new Size(200, 585); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -99,7 +106,7 @@ buttonAddPropelledArtillery.TabIndex = 1; buttonAddPropelledArtillery.Text = "Добавление бронированной машины"; buttonAddPropelledArtillery.UseVisualStyleBackColor = true; - buttonAddPropelledArtillery.Click += buttonAddPropelledArtillery_Click_1; + buttonAddPropelledArtillery.Click += buttonAddPropelledArtillery_Click; // // buttonRefresh // @@ -241,19 +248,62 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(736, 562); + pictureBox.Size = new Size(736, 585); 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(936, 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.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file | *.txt"; + // // FormPropelledArtilleryCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(936, 562); + ClientSize = new Size(936, 609); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormPropelledArtilleryCollection"; Text = "Коллекция установок"; groupBoxTools.ResumeLayout(false); @@ -262,7 +312,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -285,5 +338,11 @@ private Button buttonCollectionDel; private ListBox listBoxCollection; 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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.cs index f1cb500..b0a309f 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.cs @@ -44,7 +44,7 @@ public partial class FormPropelledArtilleryCollection : Form panelCompanyTools.Enabled = false; } - private void buttonAddPropelledArtillery_Click_1(object sender, EventArgs e) + private void buttonAddPropelledArtillery_Click(object sender, EventArgs e) { if (_company == null) { @@ -244,6 +244,39 @@ public partial class FormPropelledArtilleryCollection : 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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.resx b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.resx index af32865..2c87a36 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.resx +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 128, 21 + + + 261, 17 + \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryConfig.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryConfig.cs index 17f7199..26e5682 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryConfig.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormPropelledArtilleryConfig.cs @@ -16,7 +16,7 @@ namespace SelfPropelledArtilleryUnit; public partial class FormPropelledArtilleryConfig : Form { - private void FormPropelledArtilleryConfig_Load(object sender, EventArgs e) + public FormPropelledArtilleryConfig() { InitializeComponent(); panelRed.MouseDown += Panel_MouseDown; @@ -40,17 +40,6 @@ public partial class FormPropelledArtilleryConfig : Form /// public event Action? PropelledArtilleryDelegate; - /// - /// Конструктор - /// - public FormPropelledArtilleryConfig() - { - InitializeComponent(); - buttonCancel.Click += (sender, e) => - { - Close(); - }; - } /// /// Привязка внешнего метода к событию