diff --git a/ProjectBus/ProjectBus/CollectionGenericObjects/AbstractCompany.cs b/ProjectBus/ProjectBus/CollectionGenericObjects/AbstractCompany.cs index 5be82fe..5390df1 100644 --- a/ProjectBus/ProjectBus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectBus/ProjectBus/CollectionGenericObjects/AbstractCompany.cs @@ -28,7 +28,7 @@ namespace ProjectBoat.CollectionGenericObjects protected readonly int _pictureHeight; /// - /// Коллекция автомобилей + /// Коллекция крейсеров /// protected ICollectionGenericObjects? _collection = null; @@ -49,7 +49,7 @@ namespace ProjectBoat.CollectionGenericObjects _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectBus/ProjectBus/CollectionGenericObjects/BoatDockingService.cs b/ProjectBus/ProjectBus/CollectionGenericObjects/BoatDockingService.cs index cc989c0..549b9eb 100644 --- a/ProjectBus/ProjectBus/CollectionGenericObjects/BoatDockingService.cs +++ b/ProjectBus/ProjectBus/CollectionGenericObjects/BoatDockingService.cs @@ -22,7 +22,7 @@ namespace ProjectBoat.CollectionGenericObjects int width = _pictureWidth / _placeSizeWidth; int height = _pictureHeight / _placeSizeHeight; Pen pen = new(Color.Black, 2); - for (int i = 0; i < width + 1; i++) + for (int i = 0; i < width; i++) { for (int j = 0; j < height + 1; ++j) { diff --git a/ProjectBus/ProjectBus/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectBus/ProjectBus/CollectionGenericObjects/ICollectionGenericObjects.cs index e7a51ee..c49b5f5 100644 --- a/ProjectBus/ProjectBus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectBus/ProjectBus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -11,16 +11,19 @@ /// Количество объектов в коллекции /// int Count { get; } + /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } + /// /// Добавление объекта в коллекцию /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась int Insert(T obj); + /// /// Добавление объекта в коллекцию на конкретную позицию /// @@ -28,18 +31,31 @@ /// Позиция /// true - вставка прошла удачно, false - вставка не удалась int Insert(T obj, int position); + /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция /// true - удаление прошло удачно, false - удаление не удалось T? Remove(int position); + /// /// Получение объекта по позиции /// /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); + } } diff --git a/ProjectBus/ProjectBus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectBus/ProjectBus/CollectionGenericObjects/ListGenericObjects.cs index a1d452d..5b356c0 100644 --- a/ProjectBus/ProjectBus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectBus/ProjectBus/CollectionGenericObjects/ListGenericObjects.cs @@ -16,7 +16,20 @@ /// private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get => _maxCount; + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; + /// /// Конструктор /// @@ -61,5 +74,13 @@ _collection.RemoveAt(position); return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } } diff --git a/ProjectBus/ProjectBus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectBus/ProjectBus/CollectionGenericObjects/MassiveGenericObjects.cs index 046a56a..1803d0d 100644 --- a/ProjectBus/ProjectBus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectBus/ProjectBus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -14,8 +14,12 @@ namespace ProjectBoat.CollectionGenericObjects /// private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -32,6 +36,8 @@ namespace ProjectBoat.CollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -111,5 +117,13 @@ namespace ProjectBoat.CollectionGenericObjects _collection[position] = null; return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } } diff --git a/ProjectBus/ProjectBus/CollectionGenericObjects/StorageCollection.cs b/ProjectBus/ProjectBus/CollectionGenericObjects/StorageCollection.cs index b9b10be..e0d61e8 100644 --- a/ProjectBus/ProjectBus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectBus/ProjectBus/CollectionGenericObjects/StorageCollection.cs @@ -1,10 +1,13 @@ -namespace ProjectBoat.CollectionGenericObjects +using ProjectBoat.Drawnings; +using System.Text; + +namespace ProjectBoat.CollectionGenericObjects { // Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningBoat { /// /// Словарь (хранилище) с коллекциями @@ -16,6 +19,21 @@ /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -69,5 +87,126 @@ 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) + { + 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?.CreateDrawningBoat() is T boat) + { + if (collection.Insert(boat) == -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/ProjectBus/ProjectBus/Drawnings/DrawningBoat.cs b/ProjectBus/ProjectBus/Drawnings/DrawningBoat.cs index b9d2333..a020e87 100644 --- a/ProjectBus/ProjectBus/Drawnings/DrawningBoat.cs +++ b/ProjectBus/ProjectBus/Drawnings/DrawningBoat.cs @@ -57,7 +57,7 @@ public class DrawningBoat /// /// Пустой онструктор /// - private DrawningBoat() + public DrawningBoat() { _pictureWidth = null; _pictureHeight = null; @@ -86,6 +86,14 @@ public class DrawningBoat _pictureHeight = drawningCarHeight; } + /// + /// конструктор + /// + /// + public DrawningBoat(EntityBoat entityBoat) + { + EntityBoat = entityBoat; + } /// /// Установка границ поля /// diff --git a/ProjectBus/ProjectBus/Drawnings/DrawningMBoat.cs b/ProjectBus/ProjectBus/Drawnings/DrawningMBoat.cs index 28e4c32..90fb0d6 100644 --- a/ProjectBus/ProjectBus/Drawnings/DrawningMBoat.cs +++ b/ProjectBus/ProjectBus/Drawnings/DrawningMBoat.cs @@ -5,7 +5,6 @@ namespace ProjectBoat.Drawnings { public class DrawningMBoat : DrawningBoat { - /// /// Конструктор /// @@ -23,6 +22,13 @@ namespace ProjectBoat.Drawnings EntityBoat = new EntityMBoat(speed, weight, bodyColor, additionalColor, motor, oars, glass); } + public DrawningMBoat(EntityBoat entityBoat) + { + if (entityBoat != null) + { + EntityBoat = entityBoat; + } + } public override void DrawTransport(Graphics g) { if (EntityBoat == null || EntityBoat is not EntityMBoat entityMBoat || !_startPosX.HasValue || diff --git a/ProjectBus/ProjectBus/Drawnings/ExtentionDrawningBoat.cs b/ProjectBus/ProjectBus/Drawnings/ExtentionDrawningBoat.cs new file mode 100644 index 0000000..91a24e7 --- /dev/null +++ b/ProjectBus/ProjectBus/Drawnings/ExtentionDrawningBoat.cs @@ -0,0 +1,50 @@ +using ProjectBoat.Entities; + +namespace ProjectBoat.Drawnings +{ + public static class ExtentionDrawningBoat + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningBoat? CreateDrawningBoat(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityBoat? boat = EntityMBoat.CreateEntityMBoat(strs); + if (boat != null) + { + return new DrawningMBoat(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/ProjectBus/ProjectBus/Entities/EntityBoat.cs b/ProjectBus/ProjectBus/Entities/EntityBoat.cs index a2993c9..8717642 100644 --- a/ProjectBus/ProjectBus/Entities/EntityBoat.cs +++ b/ProjectBus/ProjectBus/Entities/EntityBoat.cs @@ -38,4 +38,27 @@ 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])); + } +} \ No newline at end of file diff --git a/ProjectBus/ProjectBus/Entities/EntityMBoat.cs b/ProjectBus/ProjectBus/Entities/EntityMBoat.cs index 0819158..72b2028 100644 --- a/ProjectBus/ProjectBus/Entities/EntityMBoat.cs +++ b/ProjectBus/ProjectBus/Entities/EntityMBoat.cs @@ -29,5 +29,30 @@ Oars = oars; Glass = glass; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityBoat), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, + Motor.ToString(), Oars.ToString(), Glass.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityBoat? CreateEntityMBoat(string[] strs) + { + if (strs.Length != 8 || strs[0] != nameof(EntityBoat)) + { + return null; + } + return new EntityMBoat(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/ProjectBus/ProjectBus/FormBoatsCollection.Designer.cs b/ProjectBus/ProjectBus/FormBoatsCollection.Designer.cs index abb36c9..ebe0201 100644 --- a/ProjectBus/ProjectBus/FormBoatsCollection.Designer.cs +++ b/ProjectBus/ProjectBus/FormBoatsCollection.Designer.cs @@ -46,10 +46,17 @@ maskedTextBoxPosision = new MaskedTextBox(); buttonGetToTest = new Button(); pictureBoxBoat = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); groupBoxTools.SuspendLayout(); panelStorage.SuspendLayout(); panelCompanyTools.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxBoat).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -59,11 +66,11 @@ groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(510, 0); + groupBoxTools.Location = new Point(552, 24); groupBoxTools.Margin = new Padding(3, 2, 3, 2); groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Padding = new Padding(3, 2, 3, 2); - groupBoxTools.Size = new Size(194, 490); + groupBoxTools.Size = new Size(194, 485); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "инструменты"; @@ -256,20 +263,65 @@ // pictureBoxBoat // pictureBoxBoat.Dock = DockStyle.Fill; - pictureBoxBoat.Location = new Point(0, 0); + pictureBoxBoat.Location = new Point(0, 24); pictureBoxBoat.Margin = new Padding(3, 2, 3, 2); pictureBoxBoat.Name = "pictureBoxBoat"; - pictureBoxBoat.Size = new Size(510, 490); + pictureBoxBoat.Size = new Size(552, 485); pictureBoxBoat.TabIndex = 1; pictureBoxBoat.TabStop = false; + pictureBoxBoat.Click += pictureBoxBoat_Click; + // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Padding = new Padding(5, 2, 0, 2); + menuStrip.Size = new Size(746, 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.Filter = "txt file|*.txt"; // // FormBoatsCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(704, 490); + ClientSize = new Size(746, 509); Controls.Add(pictureBoxBoat); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Margin = new Padding(3, 2, 3, 2); Name = "FormBoatsCollection"; Text = "FormBoatsCollection"; @@ -279,7 +331,10 @@ panelCompanyTools.ResumeLayout(false); panelCompanyTools.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxBoat).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -302,5 +357,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/ProjectBus/ProjectBus/FormBoatsCollection.cs b/ProjectBus/ProjectBus/FormBoatsCollection.cs index 4b8a883..b3f44f1 100644 --- a/ProjectBus/ProjectBus/FormBoatsCollection.cs +++ b/ProjectBus/ProjectBus/FormBoatsCollection.cs @@ -47,7 +47,7 @@ namespace ProjectBoat /// Добавление крейсера в коллекцию /// /// - private void SetBoat(DrawningBoat boat) + private void SetBoat(DrawningBoat? boat) { if (_company == null || boat == null) { @@ -222,8 +222,53 @@ namespace ProjectBoat } panelCompanyTools.Enabled = true; + } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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); + } + } + } + + private void pictureBoxBoat_Click(object sender, EventArgs e) + { + + } } } diff --git a/ProjectBus/ProjectBus/FormBoatsCollection.resx b/ProjectBus/ProjectBus/FormBoatsCollection.resx index af32865..b5b741b 100644 --- a/ProjectBus/ProjectBus/FormBoatsCollection.resx +++ b/ProjectBus/ProjectBus/FormBoatsCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 1 + + + 145, 1 + + + 310, 1 + + + 25 + \ No newline at end of file