diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs index 5bde8ce..0bdeb11 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs @@ -44,7 +44,7 @@ private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _ _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// /// Перегрузка оператора сложения для класса diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ICollectionGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ICollectionGenericObjects.cs index a19a0fc..113edbc 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ICollectionGenericObjects.cs @@ -17,10 +17,12 @@ public interface ICollectionGenericObjects /// Количество объектов в коллекции /// int Count { get; } + /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } + /// /// Добавление объекта в коллекцию /// @@ -47,4 +49,14 @@ public interface ICollectionGenericObjects /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs index 9725f20..a53a145 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs @@ -18,7 +18,10 @@ public class ListGenericObjects : ICollectionGenericObjects /// private int _maxCount; 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; + /// /// Конструктор /// @@ -28,7 +31,6 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - // TODO проверка позиции if (position >= 0 && position < Count) { return _collection[position]; @@ -64,4 +66,12 @@ public class ListGenericObjects : ICollectionGenericObjects return null; } + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } + } diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs index bc4b918..7ce31df 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs @@ -18,8 +18,13 @@ namespace ProjectCatamaran.CollectiongGenericObjects; /// private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } + set { if (value > 0) @@ -34,8 +39,11 @@ namespace ProjectCatamaran.CollectiongGenericObjects; } } } + } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -103,8 +111,16 @@ namespace ProjectCatamaran.CollectiongGenericObjects; { if (position >= _collection.Length || position < 0) { return null; } - T DrawningAircraft = _collection[position]; + T DrawningBoat = _collection[position]; _collection[position] = null; - return DrawningAircraft; + return DrawningBoat; + } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } } } diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs index 7ec2f2d..6570973 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using ProjectCatamaran.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -11,7 +12,7 @@ namespace ProjectCatamaran.CollectiongGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningBoat { /// /// Словарь (хранилище) с коллекциями @@ -21,6 +22,22 @@ public class StorageCollection /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -71,4 +88,130 @@ 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 FileStream fs = new(filename, FileMode.Create); + using StreamWriter streamWriter = new StreamWriter(fs); + streamWriter.Write(_collectionKey); + + foreach (KeyValuePair> value in _storages) + { + streamWriter.Write(Environment.NewLine); + + //не сохраняем пустые коллекции + if (value.Value.Count == 0) + { + continue; + } + + streamWriter.Write(value.Key); + streamWriter.Write(_separatorForKeyValue); + streamWriter.Write(value.Value.GetCollectionType); + streamWriter.Write(_separatorForKeyValue); + streamWriter.Write(value.Value.MaxCount); + streamWriter.Write(_separatorForKeyValue); + + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + + streamWriter.Write(data); + streamWriter.Write(_separatorItems); + + } + } + return true; + } + + + /// + /// Загрузка информации по кораблям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (StreamReader sr = new StreamReader(filename)) + + { + string? str; + str = sr.ReadLine(); + if (str != _collectionKey.ToString()) + return false; + + _storages.Clear(); + + while ((str = sr.ReadLine()) != null) + { + string[] record = str.Split(_separatorForKeyValue); + + 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?.CreateDrawningBoat() is T Truck) + { + if (collection.Insert(Truck) == -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/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs index 14a33d9..fb059ec 100644 --- a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs @@ -80,6 +80,18 @@ public class DrawningBoat /// /// /// + /// Конструктор + /// + /// Скорость + /// Вес автомобиля + /// Основной цвет public DrawningBoat(int speed, double weight, Color bodyColor) : this() { EntityBoat = new EntityBoat(speed, weight, bodyColor); diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs index 40f166f..ce6e517 100644 --- a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs @@ -25,6 +25,18 @@ public class DrawningCatamaran : DrawningBoat } + // + /// Конструктор принимающий объект Entity + /// + public DrawningCatamaran(EntityBoat? entityBoat) : base(140, 70) + { + if (entityBoat != null) + { + EntityBoat = entityBoat; + } + } + + public override void DrawTransport(Graphics g) { if (EntityBoat == null || EntityBoat is not EntityCatamaran catamaran || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/ExtentionDrawningBoat.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/ExtentionDrawningBoat.cs new file mode 100644 index 0000000..c9d7a2b --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/ExtentionDrawningBoat.cs @@ -0,0 +1,59 @@ +using ProjectCatamaran.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Drawnings; + +/// +/// Расширение для класса EntityCar +/// +public static class ExtentionDrawningBoat +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningBoat? CreateDrawningBoat(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityBoat? boat = EntityCatamaran.CreateEntityCatamaran(strs); + if (boat != null) + { + return new DrawningCatamaran(boat); + } + + boat = EntityBoat.CreateEntityBoat(strs); + if (boat != null) + { + return new DrawningBoat(boat); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawningBoat drawningBoat) + { + string[]? array = drawningBoat?.EntityBoat?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs b/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs index 0221af7..1020852 100644 --- a/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs +++ b/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs @@ -49,4 +49,28 @@ public class EntityBoat Weight = weight; BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityBoat), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityBoat? CreateEntityBoat(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityBoat)) + { + return null; + } + + return new EntityBoat(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectCatamaran/ProjectCatamaran/Entities/EntityCatamaran.cs b/ProjectCatamaran/ProjectCatamaran/Entities/EntityCatamaran.cs index 07fa9e7..8bf2db0 100644 --- a/ProjectCatamaran/ProjectCatamaran/Entities/EntityCatamaran.cs +++ b/ProjectCatamaran/ProjectCatamaran/Entities/EntityCatamaran.cs @@ -49,5 +49,29 @@ public class EntityCatamaran : EntityBoat Rightfloater = rightfloater; Sail = sail; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityCatamaran), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Leftfloater.ToString(), Rightfloater.ToString(), Sail.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityBoat? CreateEntityCatamaran(string[] strs) + { + if (strs.Length != 8 || strs[0] != nameof(EntityCatamaran)) + { + return null; + } + return new EntityCatamaran(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), + Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7])); + } } diff --git a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.Designer.cs b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.Designer.cs index b8efc31..1917bea 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.Designer.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.Designer.cs @@ -46,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBoxBoat = 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)pictureBoxBoat).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(849, 0); + groupBoxTools.Location = new Point(863, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(279, 629); + groupBoxTools.Size = new Size(279, 626); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -75,7 +82,7 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 397); + panelCompanyTools.Location = new Point(3, 394); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(273, 229); panelCompanyTools.TabIndex = 8; @@ -240,19 +247,62 @@ // pictureBoxBoat // pictureBoxBoat.Dock = DockStyle.Fill; - pictureBoxBoat.Location = new Point(0, 0); + pictureBoxBoat.Location = new Point(0, 28); pictureBoxBoat.Name = "pictureBoxBoat"; - pictureBoxBoat.Size = new Size(849, 629); + pictureBoxBoat.Size = new Size(863, 626); pictureBoxBoat.TabIndex = 1; pictureBoxBoat.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(1142, 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; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file| *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormBoatCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1128, 629); + ClientSize = new Size(1142, 654); Controls.Add(pictureBoxBoat); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBoatCollection"; Text = "Коллекция лодок"; groupBoxTools.ResumeLayout(false); @@ -261,7 +311,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxBoat).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -284,5 +337,11 @@ private RadioButton radioButtonList; private RadioButton radioButtonMassive; 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/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs index dc5bfd2..0691440 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs @@ -89,7 +89,7 @@ public partial class FormBoatCollection : Form return; } - if (MessageBox.Show("Удалить объект?", "Удаление", + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; @@ -251,4 +251,45 @@ public partial class FormBoatCollection : Form } } } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.resx b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.resx index af32865..787e76d 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.resx +++ b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 145, 17 + + + 310, 17 + + + 63 + \ No newline at end of file