diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs b/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs index a9207a7..603c506 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs @@ -50,14 +50,14 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// /// Перегрузка оператора сложения для класса /// /// Компания - /// Добавляемый объект + /// Добавляемый объект /// public static int operator +(AbstractCompany company, DrawningLocomotive locomotive) { diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs index bf02b38..f82973b 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,13 +21,13 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась -int Insert(T obj); + int Insert(T obj); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -49,4 +49,15 @@ T Remove(int position); /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs index 71b2827..4bca8bc 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs @@ -18,11 +18,26 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects /// Максимально допустимое число объектов в списке /// private int _maxCount; - - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + + public int MaxCount + { + get + { + return Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } public int Count => _collection.Count; + public CollectionType GetCollectionType => CollectionType.List; + /// /// Конструктор /// @@ -75,5 +90,12 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects return null; } + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } } diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs index 171cc19..211f9d6 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs @@ -13,13 +13,17 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects /// private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) { - if (_collection.Length > 0) + if (Count > 0) { Array.Resize(ref _collection, value); } @@ -29,8 +33,12 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects } } } + } + + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -111,5 +119,13 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects // TODO удаление объекта из массива, присвоив элементу массива значение null return Get(position); } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } } diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs index 99981af..eb6c409 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using ProjectElectricLocomotive.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -11,7 +12,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects; /// /// public class StorageCollection -where T : class +where T : DrawningLocomotive { /// @@ -78,5 +79,140 @@ where T : class 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) + { + 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?.CreateDrawningLocomotive() is T locomotive) + { + if (collection.Insert(locomotive) == -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/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs b/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs index 6fb4841..61527c6 100644 --- a/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs +++ b/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs @@ -32,7 +32,12 @@ namespace ProjectElectricLocomotive.Drawnings pantograph, batterystorage); } - + public DrawningElectricLocomotive(EntityElectricLocomotive locomotive) : base(155, 0) + { + EntityLocomotive = new EntityElectricLocomotive(locomotive.Speed, locomotive.Weight, locomotive.BodyColor, locomotive.AdditionalColor, locomotive.Pantograph, locomotive.BatteryStorage); + } + + public override void DrawTransport(Graphics g) { if (EntityLocomotive == null || EntityLocomotive is not EntityElectricLocomotive electricLocomotive || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs b/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs index 2f4c8c6..62e07f1 100644 --- a/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs +++ b/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs @@ -95,6 +95,12 @@ public class DrawningLocomotive } + public DrawningLocomotive(EntityLocomotive locomotive) : this() + { + EntityLocomotive = new EntityLocomotive(locomotive.Speed, locomotive.Weight, locomotive.BodyColor); + } + + /// /// Установка границ поля /// diff --git a/ProjectElectricLocomotive/Drawnings/ExtensionDrawningLocomotive.cs b/ProjectElectricLocomotive/Drawnings/ExtensionDrawningLocomotive.cs new file mode 100644 index 0000000..5662c48 --- /dev/null +++ b/ProjectElectricLocomotive/Drawnings/ExtensionDrawningLocomotive.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectElectricLocomotive.Entities; + +namespace ProjectElectricLocomotive.Drawnings +{ + public static class ExtensionDrawningLocomotive + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + + public static DrawningLocomotive? CreateDrawningLocomotive(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityLocomotive? locomotive = EntityElectricLocomotive.CreateEntityElectricLocomotive(strs); + if (locomotive != null) + { + return new DrawningElectricLocomotive((EntityElectricLocomotive)locomotive); + } + locomotive = EntityLocomotive.CreateEntityLocomotive(strs); + if (locomotive != null) + { + return new DrawningLocomotive(locomotive); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningLocomotive drawningLocomotive) + { + string[]? array = drawningLocomotive?.EntityLocomotive?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } + } +} diff --git a/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs b/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs index 7366f9b..a23b010 100644 --- a/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs +++ b/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs @@ -40,6 +40,31 @@ namespace ProjectElectricLocomotive.Entities Pantograph = pantograph; BatteryStorage = batteryStorage; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new string[] { nameof(EntityElectricLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Pantograph.ToString(), BatteryStorage.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityElectricLocomotive? CreateEntityElectricLocomotive(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityElectricLocomotive)) + { + return null; + } + return new EntityElectricLocomotive(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } + + internal void setAdditionalColor(Color additionalColor) { AdditionalColor = additionalColor; diff --git a/ProjectElectricLocomotive/Entities/EntityLocomotive.cs b/ProjectElectricLocomotive/Entities/EntityLocomotive.cs index 7f5eb61..ad89153 100644 --- a/ProjectElectricLocomotive/Entities/EntityLocomotive.cs +++ b/ProjectElectricLocomotive/Entities/EntityLocomotive.cs @@ -43,6 +43,30 @@ namespace ProjectElectricLocomotive.Entities } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityLocomotive? CreateEntityLocomotive(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityLocomotive)) + { + return null; + } + return new EntityLocomotive(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } + + + internal void setBodyColor(Color bodyColor) { BodyColor = bodyColor; diff --git a/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs b/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs index 8e1ebbf..a0d983a 100644 --- a/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs +++ b/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs @@ -46,10 +46,17 @@ textBoxCollectionName = new TextBox(); comboBoxSelectorCompany = new ComboBox(); pictureBox = 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)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -60,9 +67,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(589, 0); + groupBoxTools.Location = new Point(589, 33); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(503, 450); + groupBoxTools.Size = new Size(503, 417); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -234,12 +241,53 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 33); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(589, 450); + pictureBox.Size = new Size(589, 417); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(24, 24); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1092, 33); + menuStrip.TabIndex = 4; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(69, 29); + файлToolStripMenuItem.Text = "Файл"; + // + // SaveToolStripMenuItem + // + SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + SaveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + SaveToolStripMenuItem.Size = new Size(273, 34); + SaveToolStripMenuItem.Text = "Сохранение"; + SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // LoadToolStripMenuItem + // + LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + LoadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + LoadToolStripMenuItem.Size = new Size(273, 34); + LoadToolStripMenuItem.Text = "Загрузка"; + LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog1"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // // FormLocomotiveCollection // AutoScaleDimensions = new SizeF(10F, 25F); @@ -247,6 +295,8 @@ ClientSize = new Size(1092, 450); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormLocomotiveCollection"; Text = "Коллекция Локомотивов"; groupBoxTools.ResumeLayout(false); @@ -256,7 +306,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -279,5 +332,11 @@ private ListBox listBoxCollection; 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/ProjectElectricLocomotive/FormLocomotiveCollection.cs b/ProjectElectricLocomotive/FormLocomotiveCollection.cs index 569ab06..dcb5922 100644 --- a/ProjectElectricLocomotive/FormLocomotiveCollection.cs +++ b/ProjectElectricLocomotive/FormLocomotiveCollection.cs @@ -47,9 +47,9 @@ public partial class FormLocomotiveCollection : Form { panelCompanyTools.Enabled = false; } - - + + /// @@ -72,7 +72,7 @@ public partial class FormLocomotiveCollection : Form /// private void SetLocomotive(DrawningLocomotive? locomotive) { - if(_company == null || locomotive == null) + if (_company == null || locomotive == null) { return; } @@ -271,4 +271,50 @@ public partial class FormLocomotiveCollection : Form collectionType); 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/ProjectElectricLocomotive/FormLocomotiveCollection.resx b/ProjectElectricLocomotive/FormLocomotiveCollection.resx index af32865..3428ec8 100644 --- a/ProjectElectricLocomotive/FormLocomotiveCollection.resx +++ b/ProjectElectricLocomotive/FormLocomotiveCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 0 + + + 165, 0 + + + 361, 0 + + + 82 + \ No newline at end of file