diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs index a1ccc44..ae1c735 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs @@ -45,7 +45,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// /// Перегрузка оператора сложения для класса diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ICollectionGenericObject.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ICollectionGenericObject.cs index 9cc73dc..99658f2 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ICollectionGenericObject.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ICollectionGenericObject.cs @@ -18,7 +18,7 @@ public interface ICollectionGenericObject /// /// Установка макс кол-ва элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -49,4 +49,14 @@ public interface ICollectionGenericObject /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов из коллекции по одному + /// + /// + IEnumerable GetItems(); } diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs index f50ee76..0599ff4 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs @@ -22,7 +22,21 @@ public class ListGenericObjects : ICollectionGenericObject public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount { + get + { + return _collection.Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -77,4 +91,8 @@ public class ListGenericObjects : ICollectionGenericObject return obj; } + public IEnumerable GetItems() + { + for (int i = 0; i < Count; i++) yield return _collection[i]; + } } diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs index 12d0ce8..6e37fe0 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs @@ -18,8 +18,12 @@ public class MassiveGenericObjects : ICollectionGenericObject public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -36,6 +40,8 @@ public class MassiveGenericObjects : ICollectionGenericObject } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -115,4 +121,9 @@ public class MassiveGenericObjects : ICollectionGenericObject _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/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs index 3bb32cf..15ea39e 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs @@ -1,13 +1,15 @@ -using System; +using ProjectDumpTruck.Drawnings; +using System; using System.Collections.Generic; using System.Linq; +using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace ProjectDumpTruck.CollectionGenericObject; public class StorageCollection - where T : class + where T : DrawningTruck { /// /// Словарь (хранилище) с коллекциями @@ -19,6 +21,20 @@ public class StorageCollection /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + + /// /// Конструктор /// @@ -81,4 +97,115 @@ public class StorageCollection return null; } } + + public bool SaveData(string filename) + { + if (File.Exists(filename)) File.Delete(filename); + + if (_storages.Count == 0) return false; + + using (StreamWriter sw = new StreamWriter(filename)) + { + 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 (StreamReader sr = new(filename)) + { + string line = sr.ReadLine(); + + if (line == null || line.Length == 0) return false; + + if (!line.Equals(_collectionKey)) + { + //если нет такой записи, то это не те данные + return false; + } + _storages.Clear(); + + while ((line = sr.ReadLine()) != null) + { + string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + continue; + } + + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObject? 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?.CreateDrawningTruck() is T truck) + { + if (collection.Insert(truck) == -1) + { + return false; + } + } + } + _storages.Add(record[0], collection); + } + } + + return true; + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObject? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } + } + diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTruck.cs index c3f34ec..96d8ec8 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTruck.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTruck.cs @@ -25,6 +25,15 @@ public class DrawningDumpTruck : DrawningTruck { EntityTruck = new EntityDumpTruck(speed, weight, bodyColor, additionalColor, awning, tent); } + /// + /// Конструктор для класса Extention + /// + /// + public DrawningDumpTruck(EntityTruck? dumpTruck) : base(dumpTruck) + { + EntityTruck = dumpTruck; + } + public override void DrawTransport(Graphics g) { if (EntityTruck == null || EntityTruck is not EntityDumpTruck dumpTruck || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs index 9e15a42..6052d34 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs @@ -81,6 +81,15 @@ public class DrawningTruck _drawningTruckHeight= drawningTruckHeight; } + /// + /// Конструктор для класса Extention + /// + /// + public DrawningTruck(EntityTruck? truck) : this() + { + EntityTruck = truck; + } + /// /// Установка границ поля /// diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/ExtentionDrawningTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/ExtentionDrawningTruck.cs new file mode 100644 index 0000000..7eb01d2 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/ExtentionDrawningTruck.cs @@ -0,0 +1,47 @@ +using ProjectDumpTruck.Entities; +using ProjectDumpTruck.Drawnings; + +namespace ProjectDumpTruck.Drawnings; + +public static class ExtentionDrawningTruck +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningTruck? CreateDrawningTruck(this string info) + { + string[] strs = info.Split(_separatorForObject); + + EntityTruck? truck = EntityDumpTruck.CreateEntityDumpTruck(strs); + + if (truck != null) return new DrawningDumpTruck(truck); + + + truck = EntityTruck.CreateEntityTruck(strs); + + if (truck != null) return new DrawningTruck(truck); + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningTruck drawningTruck) + { + string[]? array = drawningTruck?.EntityTruck?.GetStringRepresentation(); + + if (array == null) return string.Empty; + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTruck.cs index daabf15..62329c6 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTruck.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTruck.cs @@ -42,4 +42,17 @@ public class EntityDumpTruck : EntityTruck Awning = awning; Tent = tent; } + + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityDumpTruck), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Awning.ToString() , Tent.ToString() }; + } + + public static EntityDumpTruck? CreateEntityDumpTruck(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityDumpTruck)) return null; + + return new EntityDumpTruck(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/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTruck.cs index e9f41a2..b7e4b29 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTruck.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTruck.cs @@ -51,4 +51,27 @@ public class EntityTruck Weight = weight; BodyColor = bodyColor; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityTruck), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityTruck? CreateEntityTruck(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityTruck)) + { + return null; + } + + return new EntityTruck(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.Designer.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.Designer.cs index e889451..fdafef4 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.Designer.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.Designer.cs @@ -46,10 +46,17 @@ maskedTextBoxPosition = new MaskedTextBox(); comboBoxSelectorCompany = new ComboBox(); pictureBox = 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)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -59,9 +66,9 @@ groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(888, 0); + groupBoxTools.Location = new Point(888, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(238, 688); + groupBoxTools.Size = new Size(238, 660); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -164,7 +171,7 @@ panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 385); + panelCompanyTools.Location = new Point(3, 357); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(232, 300); panelCompanyTools.TabIndex = 10; @@ -232,12 +239,53 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(888, 688); + pictureBox.Size = new Size(888, 660); pictureBox.TabIndex = 1; pictureBox.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(1126, 28); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // файл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"; + // // FormTruckCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -245,6 +293,8 @@ ClientSize = new Size(1126, 688); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormTruckCollection"; Text = "Коллекция грузовиков"; groupBoxTools.ResumeLayout(false); @@ -253,7 +303,10 @@ panelCompanyTools.ResumeLayout(false); panelCompanyTools.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -276,5 +329,11 @@ private TextBox textBoxCollectionName; private Label labelCollectionName; private Button buttonCollectionDel; + 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/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs index 1e74ff6..a35e3e0 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs @@ -238,6 +238,47 @@ public partial class FormTruckCollection : Form panelCompanyTools.Enabled = true; RefreshListBoxItems(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + 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); + RefreshListBoxItems(); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.resx b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.resx index af32865..ee1748a 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.resx +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 145, 17 + + + 310, 17 + \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTruckConfig.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTruckConfig.cs index 803f5e4..efc3ebe 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckConfig.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckConfig.cs @@ -114,7 +114,6 @@ public partial class FormTruckConfig : Form DrawObject(); } - /// /// Панель отправка цвета при нажатии на Panel