diff --git a/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs index f746200..6ace662 100644 --- a/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace AntiAircraftGun.CollectionGenereticObject; +using AntiAircraftGun.CollectionGenericObjects; + +namespace AntiAircraftGun.CollectionGenereticObject; /// /// Интерфейс описания действий для набора хранимых данных /// @@ -14,7 +16,7 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию @@ -44,4 +46,14 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs index f4a497b..29754d8 100644 --- a/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs @@ -22,10 +22,12 @@ public class ListGenericObjects : ICollectionGenericObjects public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public CollectionType GetCollectionType => CollectionType.List; + /// - /// Конструктор - /// - public ListGenericObjects() + /// Конструктор + /// + public ListGenericObjects() { _collection = new(); } @@ -58,4 +60,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs b/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs index febd359..21c30d8 100644 --- a/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -using AntiAircraftGun.Drawnings; +using AntiAircraftGun.CollectionGenericObjects; +using AntiAircraftGun.Drawnings; + namespace AntiAircraftGun.CollectionGenereticObject; /// @@ -15,8 +17,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -33,6 +39,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -128,4 +136,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } diff --git a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs index 286a131..3e2b2fc 100644 --- a/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs +++ b/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,6 @@ using AntiAircraftGun.CollectionGenereticObject; +using AntiAircraftGun.Drawnings; +using System.Text; namespace AntiAircraftGun.CollectionGenericObjects; @@ -7,7 +9,7 @@ namespace AntiAircraftGun.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningArmoredCar { /// /// Словарь (хранилище) с коллекциями @@ -18,6 +20,20 @@ public class StorageCollection /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; /// /// Конструктор @@ -67,4 +83,144 @@ public class StorageCollection return null; } } + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filename)) + { + File.Delete(filename); + } + + StringBuilder sb = new(); + + sb.Append(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + 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); + } + } + + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) + { + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) + { + bufferTextFromFile += temp.GetString(b); + } + } + + string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + return false; + } + + if (!strs[0].Equals(_collectionKey)) + { + //если нет такой записи, то это не те данные + return false; + } + + _storages.Clear(); + foreach (string data in strs) + { + string[] record = data.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?.CreateDrawningArmoredCar() is T car) + { + if (!collection.Insert(car)) + { + 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/AntiAircraftGun/Drawnings/ExtentionDrawningArmoredCar.cs b/AntiAircraftGun/Drawnings/ExtentionDrawningArmoredCar.cs new file mode 100644 index 0000000..9ec764c --- /dev/null +++ b/AntiAircraftGun/Drawnings/ExtentionDrawningArmoredCar.cs @@ -0,0 +1,58 @@ +using AntiAircraftGun.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Drawnings; +/// +/// Расширение для класса EntityArmoredCar +/// +public static class ExtentionDrawningArmoredCar +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningArmoredCar? CreateDrawningArmoredCar(this string info) + { + string[] strs = info.Split(_separatorForObject); + DrawningArmoredCar? armoredCar = EntityAntiAircraftGun.CreateEntityAntiAircraftGun(strs); + if (armoredCar != null) + { + return new DrawningAntiAircraftGun(armoredCar); + } + + armoredCar = DrawningArmoredCar.CreateEntityArmoredCar(strs); + if (armoredCar != null) + { + return new DrawningArmoredCar(armoredCar); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningArmoredCar drawningArmoredCar) + { + string[]? array = drawningArmoredCar?.EntityAircraftGun?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/AntiAircraftGun/Entities/EntityArmoredCar.cs b/AntiAircraftGun/Entities/EntityArmoredCar.cs index 8cc8c93..b52bb85 100644 --- a/AntiAircraftGun/Entities/EntityArmoredCar.cs +++ b/AntiAircraftGun/Entities/EntityArmoredCar.cs @@ -41,4 +41,27 @@ public class EntityArmoredCar Weight = weight; BodyColor = bodyColor; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityArmoredCar), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityArmoredCar? CreateEntityTrackedCar(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityArmoredCar)) + { + return null; + } + + return new EntityArmoredCar(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/AntiAircraftGun/FormArmoredCarCollection.Designer.cs b/AntiAircraftGun/FormArmoredCarCollection.Designer.cs index 7879d7d..c740677 100644 --- a/AntiAircraftGun/FormArmoredCarCollection.Designer.cs +++ b/AntiAircraftGun/FormArmoredCarCollection.Designer.cs @@ -46,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); groupBoxToools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxToools @@ -59,9 +66,9 @@ groupBoxToools.Controls.Add(panelStorage); groupBoxToools.Controls.Add(comboBoxSelectorCompany); groupBoxToools.Dock = DockStyle.Right; - groupBoxToools.Location = new Point(1057, 0); + groupBoxToools.Location = new Point(1057, 24); groupBoxToools.Name = "groupBoxToools"; - groupBoxToools.Size = new Size(210, 615); + groupBoxToools.Size = new Size(210, 591); groupBoxToools.TabIndex = 0; groupBoxToools.TabStop = false; groupBoxToools.Text = "Инструменты"; @@ -239,12 +246,52 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1057, 615); + pictureBox.Size = new Size(1057, 591); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1267, 24); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // файл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"; + // // FormArmoredCarCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -252,6 +299,8 @@ ClientSize = new Size(1267, 615); Controls.Add(pictureBox); Controls.Add(groupBoxToools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormArmoredCarCollection"; Text = "Коллекция бронемашин"; groupBoxToools.ResumeLayout(false); @@ -260,7 +309,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -283,5 +335,11 @@ private ListBox listBoxCollection; 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/AntiAircraftGun/FormArmoredCarCollection.cs b/AntiAircraftGun/FormArmoredCarCollection.cs index 788bae7..d1517bd 100644 --- a/AntiAircraftGun/FormArmoredCarCollection.cs +++ b/AntiAircraftGun/FormArmoredCarCollection.cs @@ -242,5 +242,44 @@ public partial class FormArmoredCarCollection : 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); + } + } + } } diff --git a/AntiAircraftGun/FormArmoredCarCollection.resx b/AntiAircraftGun/FormArmoredCarCollection.resx index af32865..8b1dfa1 100644 --- a/AntiAircraftGun/FormArmoredCarCollection.resx +++ b/AntiAircraftGun/FormArmoredCarCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 261, 17 + \ No newline at end of file