diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/AbstractCompany.cs b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/AbstractCompany.cs index 013d334..929d05a 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/AbstractCompany.cs @@ -39,7 +39,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// /// Перегрузка оператора сложения для класса diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/ICollectionGenericObjects.cs index bca9d15..5ffe4cc 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -10,7 +10,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { set; get; } /// /// Добавление объекта в коллекцию /// @@ -36,4 +36,13 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/ListGenericObjects.cs b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/ListGenericObjects.cs index 18f2c09..c2b5294 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/ListGenericObjects.cs @@ -7,12 +7,25 @@ public class ListGenericObjects : ICollectionGenericObjects /// Список объектов, которые храним /// private readonly List _collection; + public CollectionType GetCollectionType => CollectionType.List; /// /// Максимально допустимое число объектов в списке /// private int _maxCount; 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; + } + } + } /// /// Конструктор /// @@ -53,4 +66,11 @@ 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/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs index 99cea55..6199165 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/MassiveGenericObjects.cs @@ -8,8 +8,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects /// private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount + public CollectionType GetCollectionType => CollectionType.Massive; + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -99,4 +104,11 @@ 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/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/StorageCollection.cs b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/StorageCollection.cs index 60d96f4..cc77b06 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/CollectionGenericObjects/StorageCollection.cs @@ -1,9 +1,11 @@ using ProjectWarmlyShip.Drawnings; +using System.Text; +using static System.Runtime.InteropServices.JavaScript.JSType; namespace ProjectWarmlyShip.CollectionGenericObjects; public class StorageCollection - where T : class + where T : DrawningShip { /// /// Словарь (хранилище) с коллекциями @@ -44,7 +46,7 @@ public class StorageCollection { // TODO Прописать логику для удаления коллекции - if (_storages.ContainsKey(name)) + if (_storages.ContainsKey(name)) _storages.Remove(name); } /// @@ -62,4 +64,130 @@ public class StorageCollection return null; } } + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// 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) + { + writer.Write(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) + { + continue; + } + 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); + } + } + } + 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) + { + 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?.CreateDrawningShip() 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/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/DrawningShip.cs b/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/DrawningShip.cs index 4fe08b1..bfd1c4e 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/DrawningShip.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/DrawningShip.cs @@ -78,6 +78,10 @@ public class DrawningShip this._drawningShipWidth= _drawningShipWidth; this._drawningShipHeight = _drawnShipHeight; } + public DrawningShip(EntityShip ship) : this() + { + EntityShip = new EntityShip(ship.Speed, ship.Weight, ship.BodyColor); + } public bool SetPictureSize(int width, int height) { // TODO проверка, что объект "влезает" в размеры поля diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/DrawningWarmlyShip.cs b/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/DrawningWarmlyShip.cs index fd00dc6..33e7fbf 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/DrawningWarmlyShip.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/DrawningWarmlyShip.cs @@ -14,6 +14,10 @@ public class DrawningWarmlyShip : DrawningShip { EntityShip = new EntityWarmlyShip(speed, weight, bodycolor, additionalcolor, shpipipes, fueltank); //дописать конструктор } + public DrawningWarmlyShip(EntityWarmlyShip ship) : base(150, 80) + { + EntityShip = new EntityWarmlyShip(ship.Speed, ship.Weight, ship.BodyColor, ship.AdditionalColor, ship.ShipPipes, ship.FuelTank); + } public override void DrawTransport(Graphics g) { //оператор is совместимость объекта с заданным типом diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/ExtentionDrawningShip.cs b/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/ExtentionDrawningShip.cs new file mode 100644 index 0000000..abffbce --- /dev/null +++ b/ProjectWarmlyShip/ProjectWarmlyShip/Drawnings/ExtentionDrawningShip.cs @@ -0,0 +1,48 @@ +using ProjectWarmlyShip.Entities; + +namespace ProjectWarmlyShip.Drawnings; + +/// +/// Расширение для класса EntityCar +/// +public static class ExtentionDrawningShip +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningShip? CreateDrawningShip(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityShip? ship = EntityWarmlyShip.CreateEntityWarmlyShip(strs); + if (ship != null) + { + return new DrawningWarmlyShip((EntityWarmlyShip)ship); + } + ship = EntityShip.CreateEntityShip(strs); + if (ship != null) + { + return new DrawningShip(ship); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningShip drawningCar) + { + string[]? array = drawningCar?.EntityShip?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/Entities/EntityShip.cs b/ProjectWarmlyShip/ProjectWarmlyShip/Entities/EntityShip.cs index bf228a9..080c7f0 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/Entities/EntityShip.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/Entities/EntityShip.cs @@ -34,5 +34,27 @@ public class EntityShip Weight = weight; BodyColor = bodycolor; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityShip), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityShip? CreateEntityShip(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityShip)) + { + return null; + } + return new EntityShip(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } + diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/Entities/EntityWarmlyShip.cs b/ProjectWarmlyShip/ProjectWarmlyShip/Entities/EntityWarmlyShip.cs index 8a76f1a..8e45e9d 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/Entities/EntityWarmlyShip.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/Entities/EntityWarmlyShip.cs @@ -30,4 +30,27 @@ public class EntityWarmlyShip : EntityShip ShipPipes = shpipipes; FuelTank = fueltank; } + /// + /// Получение строк со значениями свойств продвинутого объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityWarmlyShip), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, + ShipPipes.ToString(), FuelTank.ToString()}; + } + /// + /// Создание продвинутого объекта из массива строк + /// + /// + /// + public static EntityWarmlyShip? CreateEntityWarmlyShip(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityWarmlyShip)) + { + return null; + } + return new EntityWarmlyShip(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/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.Designer.cs b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.Designer.cs index a823314..9ecf501 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.Designer.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.Designer.cs @@ -46,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + FileToolStripMenuItem = 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 @@ -58,9 +65,9 @@ groupBoxTools.Controls.Add(buttonCreateCompany); groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(887, 0); + groupBoxTools.Location = new Point(887, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(146, 596); + groupBoxTools.Size = new Size(146, 597); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -239,19 +246,61 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(887, 596); + pictureBox.Size = new Size(887, 597); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1033, 24); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // FileToolStripMenuItem + // + FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + FileToolStripMenuItem.Name = "FileToolStripMenuItem"; + FileToolStripMenuItem.Size = new Size(48, 20); + FileToolStripMenuItem.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"; + // // FormShipCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1033, 596); + ClientSize = new Size(1033, 621); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormShipCollection"; Text = "Коллекция судов"; groupBoxTools.ResumeLayout(false); @@ -260,7 +309,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -283,5 +335,11 @@ private ListBox listBoxCollection; private Button buttonCollectionAdd; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem FileToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; } } \ No newline at end of file diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs index 03f710b..443544e 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs @@ -168,5 +168,38 @@ public partial class FormShipCollection : 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/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.resx b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.resx index af32865..8b1dfa1 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.resx +++ b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.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 diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipConfig.Designer.cs b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipConfig.Designer.cs index d14073c..3e02e3d 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipConfig.Designer.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipConfig.Designer.cs @@ -146,7 +146,7 @@ // // panelGreen // - panelGreen.BackColor = Color.FromArgb(0, 192, 0); + panelGreen.BackColor = Color.Green; panelGreen.Location = new Point(65, 22); panelGreen.Name = "panelGreen"; panelGreen.Size = new Size(35, 32);