diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs index ba86553..172b0c8 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs @@ -54,7 +54,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ICollectionGenericObjects.cs index 4e9086c..bcb6538 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -15,7 +15,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -45,4 +45,10 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + CollectionType GetCollectionType { get; } + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs index 98254ee..58ab71b 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs @@ -19,7 +19,22 @@ public class ListGenericObjects : ICollectionGenericObjects private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get + { + return Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; /// /// Конструктор @@ -46,7 +61,13 @@ public class ListGenericObjects : ICollectionGenericObjects return 1; } - + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } public int Insert(T obj, int position) { if (_collection.Count + 1 < _maxCount) { return 0; } diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs index a6559b1..d46bcae 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs @@ -14,8 +14,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } + set { if (value > 0) @@ -30,8 +35,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } - } + } + public CollectionType GetCollectionType => CollectionType.Massive; public MassiveGenericObjects() { _collection = Array.Empty(); @@ -107,15 +113,16 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Remove(int position) { - if (position < 0 || position >= Count) - { - return null; - } - - if (_collection[position] == null) return null; - - T? temp = _collection[position]; + if (position >= Count || position < 0) return null; + T? myObject = _collection[position]; _collection[position] = null; - return temp; + return myObject; + } + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } } } \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs index 07b3d56..a0a5463 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectRoadTrain.CollectionGenericObjects; +using ProjectRoadTrain.Drawnings; using System; using System.Collections.Generic; using System.Linq; @@ -6,7 +7,7 @@ using System.Text; using System.Threading.Tasks; public class StorageCollection - where T : class + where T : DrawningTrain { readonly Dictionary> _storages; @@ -21,19 +22,12 @@ public class StorageCollection public void AddCollection(string name, CollectionType collectionType) { - if (name == null || _storages.ContainsKey(name)) { return; } - switch (collectionType) - - { - case CollectionType.None: - return; - case CollectionType.Massive: - _storages.Add(name, new MassiveGenericObjects { }); - return; - case CollectionType.List: - _storages.Add(name, new ListGenericObjects { }); - return; - } + if (_storages.ContainsKey(name)) return; + if (collectionType == CollectionType.None) return; + else if (collectionType == CollectionType.Massive) + _storages[name] = new MassiveGenericObjects(); + else if (collectionType == CollectionType.List) + _storages[name] = new ListGenericObjects(); } public void DelCollection(string name) @@ -46,8 +40,133 @@ public class StorageCollection { get { - if (name == null || !_storages.ContainsKey(name)) { return null; } - return _storages[name]; + if (_storages.ContainsKey(name)) + return _storages[name]; + return null; } } + private readonly string _collectionKey = "CollectionsStorage"; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + 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?.CreateTrain() is T machine) + { + if (collection.Insert(machine) == -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/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawningRoadTrain.cs b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawningRoadTrain.cs index f5efda3..63f3875 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawningRoadTrain.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawningRoadTrain.cs @@ -9,12 +9,19 @@ namespace ProjectRoadTrain.Drawnings; public class DrawningRoadTrain : DrawningTrain { - - public DrawningRoadTrain(int speed, double weight, Color bodycolor, Color bodytankcolor, bool watertank, bool cleanbrush) : base(230, 115) { EntityTrain = new EntityRoadTrain(speed, weight, bodycolor, bodytankcolor, watertank, cleanbrush); } + public DrawningRoadTrain(EntityRoadTrain entityRoadTrain) : base(180, 140) + { + EntityTrain = new EntityRoadTrain(entityRoadTrain.Speed, entityRoadTrain.Weight, entityRoadTrain.BodyColor, entityRoadTrain.BodyTankColor, entityRoadTrain.WaterTank, entityRoadTrain.CleanBrush); + } + //public DrawningRoadTrain(EntityRoadTrain roadTrain) : base(180, 140) + //{ + // EntityTrain = new EntityRoadTrain(roadTrain.Speed, roadTrain.Weight, roadTrain.BodyColor, roadTrain.BodyTankColor, roadTrain.WaterTank, roadTrain.CleanBrush); + //} + diff --git a/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawningTrain.cs b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawningTrain.cs index e2af3cf..24e0119 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawningTrain.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/DrawningTrain.cs @@ -45,6 +45,10 @@ public class DrawningTrain _startPosX = null; _startPosY = null; } + public DrawningTrain(EntityTrain train) : this() + { + EntityTrain = new EntityTrain(train.Speed, train.Weight, train.BodyColor); + } public DrawningTrain(int speed, double weight, Color bodycolor) : this() { EntityTrain = new EntityTrain(speed, weight, bodycolor); diff --git a/ProjectRoadTrain/ProjectRoadTrain/Drawnings/ExtentionDrawningTrain.cs b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/ExtentionDrawningTrain.cs new file mode 100644 index 0000000..406922b --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Drawnings/ExtentionDrawningTrain.cs @@ -0,0 +1,58 @@ +using ProjectRoadTrain.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Drawnings; + +/// +/// Расширение для класса EntityCar +/// +public static class ExtentionDrawningMachine +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningTrain? CreateTrain(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityTrain? machine = EntityRoadTrain.CreateEntityRoadTrain(strs); + if (machine != null) + { + return new DrawningRoadTrain((EntityRoadTrain)machine); + } + machine = EntityTrain.CreateEntityTrain(strs); + if (machine != null) + { + return new DrawningTrain(machine); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningTrain drawningTrackedMachine) + { + string[]? array = drawningTrackedMachine?.EntityTrain?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + + } + return string.Join(_separatorForObject, array); + } + +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Entities/EntityRoadTrain.cs b/ProjectRoadTrain/ProjectRoadTrain/Entities/EntityRoadTrain.cs index a805650..1d0da1d 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/Entities/EntityRoadTrain.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/Entities/EntityRoadTrain.cs @@ -1,6 +1,6 @@ namespace ProjectRoadTrain.Entities; -internal class EntityRoadTrain : EntityTrain +public class EntityRoadTrain : EntityTrain { public Color BodyTankColor { get; private set; } public bool WaterTank { get; private set; } @@ -10,6 +10,26 @@ internal class EntityRoadTrain : EntityTrain { BodyTankColor = color; } + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityRoadTrain), Speed.ToString(), Weight.ToString(), BodyColor.Name, BodyTankColor.Name, + WaterTank.ToString(), CleanBrush.ToString()}; + } + + /// + /// Создание продвинутого объекта из массива строк + /// + /// + /// + public static EntityRoadTrain? CreateEntityRoadTrain(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityRoadTrain)) + { + return null; + } + return new EntityRoadTrain(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), + Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } public EntityRoadTrain(int speed, double weight, Color bodycolor, Color bodytankcolor, bool watertank, bool cleanbrush) : base(speed, weight, bodycolor) diff --git a/ProjectRoadTrain/ProjectRoadTrain/Entities/EntityTrain.cs b/ProjectRoadTrain/ProjectRoadTrain/Entities/EntityTrain.cs index 69a9fc7..6652642 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/Entities/EntityTrain.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/Entities/EntityTrain.cs @@ -12,6 +12,25 @@ public class EntityTrain { BodyColor = color; } + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityTrain), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityTrain? CreateEntityTrain(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityTrain)) + { + return null; + } + + return new EntityTrain(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } public int Speed { get; private set; } public double Weight { get; private set; } public Color BodyColor { get; private set; } diff --git a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs index 185e615..7b2b101 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs @@ -1,4 +1,6 @@ -namespace ProjectRoadTrain +using System.Windows.Forms; + +namespace ProjectRoadTrain { partial class FormTrainCollection { @@ -65,6 +67,57 @@ groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "инструменты"; + // menuStrip + // + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + PerformLayout(); + 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(980, 28); + menuStrip.TabIndex = 6; + 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"; // // panelCompanyTools // @@ -284,5 +337,11 @@ private Button buttonCollectionDel; private Button buttonCreateCompany; 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/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs index 87e5f3f..1ea003b 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs @@ -256,7 +256,45 @@ namespace ProjectRoadTrain _storageCollection.AddCollection(textBoxCollectionName.Text, 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) + { + // TODO продумать логику + 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 ButtonCollectionDel_Click(object sender, EventArgs e) { if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) diff --git a/ProjectRoadTrain/ProjectRoadTrain/FormTrainConfig.cs b/ProjectRoadTrain/ProjectRoadTrain/FormTrainConfig.cs index fdb58e1..ebef068 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/FormTrainConfig.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/FormTrainConfig.cs @@ -6,6 +6,7 @@ using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; +using System.Reflection.PortableExecutable; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; @@ -114,10 +115,8 @@ public partial class FormTrainConfig : Form } private void labelBodyTankColor_DragDrop(object sender, DragEventArgs e) { - if (_train.EntityTrain is EntityRoadTrain _waterTank) - { - _waterTank.setBodyTankColor((Color)e.Data.GetData(typeof(Color))); - } + if (_train != null && _train.EntityTrain is EntityRoadTrain _bulldozer) + _bulldozer.setBodyTankColor((Color)e.Data.GetData(typeof(Color))); DrawObject(); }