diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ICollectionGenericObjects.cs index 776e2ad..faf079d 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -15,7 +15,7 @@ /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -45,5 +45,16 @@ /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs index 4a772c4..771318d 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs @@ -16,7 +16,10 @@ public class ListGenericObjects : ICollectionGenericObjects /// private int _maxCount; public int Count => _collection.Keys.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount { set { if (value > 0) { _maxCount = value; } } } + + public CollectionType GetCollectionType => CollectionType.List; + /// /// Конструктор /// @@ -48,4 +51,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.Remove(position); return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs index 661b751..4b6ba22 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs @@ -15,7 +15,7 @@ namespace ProjectLiner.CollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { set { @@ -33,6 +33,8 @@ namespace ProjectLiner.CollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -105,5 +107,13 @@ namespace ProjectLiner.CollectionGenericObjects _collection[position] = null; return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs index 6e2ed1a..08bacf4 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs @@ -1,26 +1,45 @@ using ProjectLiner.CollectionGenericObjects; +using ProjectLiner.Drawnings; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningCommonLiner { /// /// Словарь (хранилище) с коллекциями /// readonly Dictionary> _storages; + /// /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// public StorageCollection() { _storages = new Dictionary>(); + } /// /// Добавление коллекции в хранилище @@ -65,4 +84,125 @@ public class StorageCollection return _storages[name]; } } + + /// + /// Сохранение информации по лайнерам в хранилище в файл + /// + /// Путь и имя файла + /// 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 sw = new StreamWriter(fs); + sw.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + sw.Write(Environment.NewLine); + if (value.Value.Count == 0) + { + continue; + } + + sw.Write(value.Key); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.GetCollectionType); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.MaxCount); + sw.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sw.Write(data); + sw.Write(_separatorItems); + } + } + return true; + } + + /// + /// Загрузка информации по лайнерам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (FileStream fs = new(filename, FileMode.Open)) + { + using StreamReader sr = new StreamReader(fs); + + string str = sr.ReadLine(); + if (str == null || str.Length == 0) + { + return false; + } + + if (!str.Equals(_collectionKey)) + { + return false; + } + _storages.Clear(); + + while (!sr.EndOfStream) + { + string[] record = sr.ReadLine().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?.CreateDrawningCommonLiner() is T commonLiner) + { + if (collection.Insert(commonLiner) == -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, + }; + } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/Drawnings/DrawningCommonLiner.cs b/ProjectLiner/ProjectLiner/Drawnings/DrawningCommonLiner.cs index ef854f9..7ae9fb3 100644 --- a/ProjectLiner/ProjectLiner/Drawnings/DrawningCommonLiner.cs +++ b/ProjectLiner/ProjectLiner/Drawnings/DrawningCommonLiner.cs @@ -98,6 +98,17 @@ public class DrawningCommonLiner _drawningLinerWidth = drawningLinerWight; } + + /// + /// Конструктор для метода создания объекта из строки (ExtentionDrawningCommonLiner) + /// + /// + public DrawningCommonLiner(EntityCommonLiner? CommonLiner) : this() + { + EntityCommonLiner = CommonLiner; + } + + /// /// Установка границ поля /// diff --git a/ProjectLiner/ProjectLiner/Drawnings/DrawningLiner.cs b/ProjectLiner/ProjectLiner/Drawnings/DrawningLiner.cs index 46a4021..1060d71 100644 --- a/ProjectLiner/ProjectLiner/Drawnings/DrawningLiner.cs +++ b/ProjectLiner/ProjectLiner/Drawnings/DrawningLiner.cs @@ -23,6 +23,16 @@ public class DrawningLiner : DrawningCommonLiner } + /// + /// Конструктор для метода создания объекта из строки (ExtentionDrawningAirplane) + /// + /// + public DrawningLiner(EntityCommonLiner? liner) : base(liner) + { + if (liner != null) + EntityCommonLiner = liner; + } + public override void DrawTransport(Graphics g) { if (EntityCommonLiner == null || EntityCommonLiner is not EntityLiner liner || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectLiner/ProjectLiner/Drawnings/ExtentionDrawningLiner.cs b/ProjectLiner/ProjectLiner/Drawnings/ExtentionDrawningLiner.cs new file mode 100644 index 0000000..e1839a8 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Drawnings/ExtentionDrawningLiner.cs @@ -0,0 +1,53 @@ +using ProjectLiner.Entities; + +namespace ProjectLiner.Drawnings; + +public static class ExtentionDrawningLiner +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningCommonLiner? CreateDrawningCommonLiner(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityCommonLiner? CommonLiner = EntityLiner.CreateEntityLiner(strs); + + if (CommonLiner != null) + { + return new DrawningLiner(CommonLiner); + } + + CommonLiner = EntityCommonLiner.CreateEntityCommonLiner(strs); + + if (CommonLiner != null) + { + return new DrawningCommonLiner(CommonLiner); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningCommonLiner drawningCommonLiner) + { + string[]? array = drawningCommonLiner?.EntityCommonLiner?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectLiner/ProjectLiner/Entities/EntityCommonLiner.cs b/ProjectLiner/ProjectLiner/Entities/EntityCommonLiner.cs index d246314..c360ac5 100644 --- a/ProjectLiner/ProjectLiner/Entities/EntityCommonLiner.cs +++ b/ProjectLiner/ProjectLiner/Entities/EntityCommonLiner.cs @@ -55,5 +55,27 @@ namespace ProjectLiner.Entities { BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityCommonLiner), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityCommonLiner? CreateEntityCommonLiner(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityCommonLiner)) + return null; + + return new EntityCommonLiner(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } } diff --git a/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs b/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs index b2308db..0b44be7 100644 --- a/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs +++ b/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs @@ -1,4 +1,6 @@ -namespace ProjectLiner.Entities; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + +namespace ProjectLiner.Entities; /// /// Класс-сущность "Лайнер" @@ -51,4 +53,29 @@ public class EntityLiner: EntityCommonLiner { AdditionalColor = additionalColor; } + + /// + /// Переопределение метода создания объекта из массива строк + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityLiner), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Anchor.ToString(), Boats.ToString(), Pipe.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityLiner? CreateEntityLiner(string[] strs) + { + if (strs.Length != 8 || strs[0] != nameof(EntityLiner)) + return null; + + return new EntityLiner(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])); + } + } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs index ed95089..ad3a8cc 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs @@ -46,10 +46,17 @@ button5 = new Button(); button3 = new Button(); button4 = new Button(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + openFileDialog = new OpenFileDialog(); + saveFileDialog = new SaveFileDialog(); groupBoxTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); panelCompanyTools.SuspendLayout(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -58,9 +65,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(1052, 0); + groupBoxTools.Location = new Point(1052, 49); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(272, 1063); + groupBoxTools.Size = new Size(272, 1014); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -183,9 +190,9 @@ // pictureBox.Dock = DockStyle.Bottom; pictureBox.Enabled = false; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 51); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1052, 1063); + pictureBox.Size = new Size(1052, 1012); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -197,10 +204,10 @@ panelCompanyTools.Controls.Add(button5); panelCompanyTools.Controls.Add(button3); panelCompanyTools.Controls.Add(button4); - panelCompanyTools.Location = new Point(1052, 567); + panelCompanyTools.Location = new Point(1052, 592); panelCompanyTools.Margin = new Padding(5); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(272, 495); + panelCompanyTools.Size = new Size(272, 470); panelCompanyTools.TabIndex = 9; // // buttonAddLiner @@ -255,6 +262,48 @@ button4.UseVisualStyleBackColor = true; button4.Click += ButtonGoToCheck_Click; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(26, 26); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1324, 49); + menuStrip.TabIndex = 10; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(104, 45); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(399, 50); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(399, 50); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // // FormLinerCollection // AutoScaleDimensions = new SizeF(17F, 41F); @@ -263,6 +312,8 @@ Controls.Add(panelCompanyTools); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormLinerCollection"; Text = "Коллекция автомобилей"; groupBoxTools.ResumeLayout(false); @@ -271,7 +322,10 @@ ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); panelCompanyTools.ResumeLayout(false); panelCompanyTools.PerformLayout(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -298,5 +352,11 @@ private Button button3; private Button button4; private Button buttonAddLiner; + 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/ProjectLiner/ProjectLiner/FormLinerCollection.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.cs index cd5b2c0..8208c72 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.cs @@ -1,6 +1,7 @@  using ProjectLiner.CollectionGenericObjects; using ProjectLiner.Drawnings; +using System.Windows.Forms; namespace ProjectLiner; /// @@ -222,4 +223,45 @@ public partial class FormLinerCollection : 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); + } + } + } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.resx b/ProjectLiner/ProjectLiner/FormLinerCollection.resx index af32865..1b18cc5 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.resx +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 228, 17 + + + 519, 17 + \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLinerConfig.cs b/ProjectLiner/ProjectLiner/FormLinerConfig.cs index c09b8b8..01722d3 100644 --- a/ProjectLiner/ProjectLiner/FormLinerConfig.cs +++ b/ProjectLiner/ProjectLiner/FormLinerConfig.cs @@ -1,6 +1,7 @@  using ProjectLiner.Drawnings; using ProjectLiner.Entities; +using static System.Runtime.InteropServices.JavaScript.JSType; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; namespace ProjectLiner;