diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs index a65fb60..c9f54cf 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs @@ -38,6 +38,10 @@ namespace AirplaneWithRadar.Generics /// private readonly SetGeneric _collection; /// + /// Получение объектов коллекции + /// + public IEnumerable GetAirplanes => _collection.GetAirplanes(); + /// /// Конструктор /// /// diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs index c15272c..1f5ae6d 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs @@ -31,6 +31,18 @@ namespace AirplaneWithRadar.Generics /// private readonly int _pictureHeight; /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// /// Конструктор /// /// @@ -42,6 +54,7 @@ namespace AirplaneWithRadar.Generics _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } + /// /// Добавление набора /// @@ -78,5 +91,98 @@ namespace AirplaneWithRadar.Generics return null; } } + /// + /// Сохранение информации по самолетам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in _airplaneStorages) + { + StringBuilder records = new(); + foreach (DrawningAirplane? elem in record.Value.GetAirplanes) + { + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } + if (data.Length == 0) + { + return false; + } + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new + UTF8Encoding(true).GetBytes($"AirplaneStorage{Environment.NewLine}{data}"); + 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); + } + } + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, + StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + return false; + } + if (!strs[0].StartsWith("AirplaneStorage")) + { + //если нет такой записи, то это не те данные + return false; + } + _airplaneStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + AirplanesGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, + StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningAirplane? airplane = + elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight); + if (airplane != null) + { + if (!(collection + airplane)) + { + return false; + } + } + } + _airplaneStorages.Add(record[0], collection); + } + return true; + } } } diff --git a/AirplaneWithRadar/AirplaneWithRadar/ExtentionDrawningAirplane.cs b/AirplaneWithRadar/AirplaneWithRadar/ExtentionDrawningAirplane.cs new file mode 100644 index 0000000..d5bfcea --- /dev/null +++ b/AirplaneWithRadar/AirplaneWithRadar/ExtentionDrawningAirplane.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AirplaneWithRadar.DrawningObjects; +using AirplaneWithRadar.Entities; + +namespace AirplaneWithRadar.DrawningObjects +{ + public static class ExtentionDrawningAirplane + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель даннных + /// Ширина + /// Высота + /// Объект + public static DrawningAirplane? CreateDrawningAirplane(this string info, char + separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3) + { + return new DrawningAirplane(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height); + } + if (strs.Length == 7) + { + return new DrawningAirplaneWithRadar(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), + Color.FromName(strs[2]), + Color.FromName(strs[3]), + Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5]), + Convert.ToBoolean(strs[6]), width, height); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Разделитель даннных + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningAirplane drawningAirplane, + char separatorForObject) + { + var airplane = drawningAirplane.EntityAirplane; + if (airplane == null) + { + return string.Empty; + + } + var str =$"{airplane.Speed}{separatorForObject}{airplane.Weight}{separatorForObject}{airplane.BodyColor.Name}"; + if (airplane is not EntityAirplaneWithRadar airplaneWithRadar) + { + return str; + } + return $"{str}{separatorForObject}{airplaneWithRadar.AdditionalColor.Name}" + + $"{separatorForObject}{airplaneWithRadar.Radar}{separatorForObject}" + + $"{airplaneWithRadar.Tank}{separatorForObject}{airplaneWithRadar.Pin}"; + } + } +} diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.Designer.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.Designer.cs index 48be20a..94d8463 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.Designer.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.Designer.cs @@ -38,9 +38,16 @@ buttonUpdate = new Button(); buttonAdd = new Button(); buttonDelete = new Button(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + сохранениеToolStripMenuItem = new ToolStripMenuItem(); + загрузкаToolStripMenuItem = new ToolStripMenuItem(); pictureBoxCollection = new PictureBox(); + openFileDialog = new OpenFileDialog(); + saveFileDialog = new SaveFileDialog(); groupBoxInstruments.SuspendLayout(); groupBoxSets.SuspendLayout(); + menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); SuspendLayout(); // @@ -51,12 +58,13 @@ groupBoxInstruments.Controls.Add(buttonUpdate); groupBoxInstruments.Controls.Add(buttonAdd); groupBoxInstruments.Controls.Add(buttonDelete); + groupBoxInstruments.Controls.Add(menuStrip); groupBoxInstruments.Dock = DockStyle.Right; - groupBoxInstruments.Location = new Point(707, 0); + groupBoxInstruments.Location = new Point(619, 0); groupBoxInstruments.Margin = new Padding(2); groupBoxInstruments.Name = "groupBoxInstruments"; groupBoxInstruments.Padding = new Padding(2); - groupBoxInstruments.Size = new Size(214, 570); + groupBoxInstruments.Size = new Size(187, 534); groupBoxInstruments.TabIndex = 5; groupBoxInstruments.TabStop = false; groupBoxInstruments.Text = "Инструменты"; @@ -67,19 +75,21 @@ groupBoxSets.Controls.Add(listBoxStorages); groupBoxSets.Controls.Add(buttonAddInSet); groupBoxSets.Controls.Add(textBoxStorageName); - groupBoxSets.Location = new Point(14, 33); + groupBoxSets.Location = new Point(17, 118); + groupBoxSets.Margin = new Padding(3, 2, 3, 2); groupBoxSets.Name = "groupBoxSets"; - groupBoxSets.Size = new Size(182, 313); + groupBoxSets.Padding = new Padding(3, 2, 3, 2); + groupBoxSets.Size = new Size(159, 235); groupBoxSets.TabIndex = 6; groupBoxSets.TabStop = false; groupBoxSets.Text = "Наборы"; // // buttonDeleteSet // - buttonDeleteSet.Location = new Point(9, 223); + buttonDeleteSet.Location = new Point(8, 167); buttonDeleteSet.Margin = new Padding(2); buttonDeleteSet.Name = "buttonDeleteSet"; - buttonDeleteSet.Size = new Size(166, 30); + buttonDeleteSet.Size = new Size(145, 22); buttonDeleteSet.TabIndex = 9; buttonDeleteSet.Text = "Удалить набор"; buttonDeleteSet.UseVisualStyleBackColor = true; @@ -88,19 +98,20 @@ // listBoxStorages // listBoxStorages.FormattingEnabled = true; - listBoxStorages.ItemHeight = 20; - listBoxStorages.Location = new Point(14, 111); + listBoxStorages.ItemHeight = 15; + listBoxStorages.Location = new Point(12, 83); + listBoxStorages.Margin = new Padding(3, 2, 3, 2); listBoxStorages.Name = "listBoxStorages"; - listBoxStorages.Size = new Size(152, 84); + listBoxStorages.Size = new Size(134, 64); listBoxStorages.TabIndex = 8; listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged; // // buttonAddInSet // - buttonAddInSet.Location = new Point(9, 65); + buttonAddInSet.Location = new Point(8, 49); buttonAddInSet.Margin = new Padding(2); buttonAddInSet.Name = "buttonAddInSet"; - buttonAddInSet.Size = new Size(166, 30); + buttonAddInSet.Size = new Size(145, 22); buttonAddInSet.TabIndex = 7; buttonAddInSet.Text = "Добавить в набор"; buttonAddInSet.UseVisualStyleBackColor = true; @@ -108,25 +119,26 @@ // // textBoxStorageName // - textBoxStorageName.Location = new Point(9, 33); + textBoxStorageName.Location = new Point(8, 25); + textBoxStorageName.Margin = new Padding(3, 2, 3, 2); textBoxStorageName.Name = "textBoxStorageName"; - textBoxStorageName.Size = new Size(162, 27); + textBoxStorageName.Size = new Size(142, 23); textBoxStorageName.TabIndex = 0; // // maskedTextBoxNumber // - maskedTextBoxNumber.Location = new Point(51, 425); + maskedTextBoxNumber.Location = new Point(50, 412); maskedTextBoxNumber.Margin = new Padding(2); maskedTextBoxNumber.Name = "maskedTextBoxNumber"; - maskedTextBoxNumber.Size = new Size(119, 27); + maskedTextBoxNumber.Size = new Size(105, 23); maskedTextBoxNumber.TabIndex = 5; // // buttonUpdate // - buttonUpdate.Location = new Point(38, 509); + buttonUpdate.Location = new Point(38, 475); buttonUpdate.Margin = new Padding(2); buttonUpdate.Name = "buttonUpdate"; - buttonUpdate.Size = new Size(142, 50); + buttonUpdate.Size = new Size(124, 38); buttonUpdate.TabIndex = 4; buttonUpdate.Text = "Обновить коллекцию"; buttonUpdate.UseVisualStyleBackColor = true; @@ -134,10 +146,10 @@ // // buttonAdd // - buttonAdd.Location = new Point(30, 369); + buttonAdd.Location = new Point(31, 370); buttonAdd.Margin = new Padding(2); buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(166, 30); + buttonAdd.Size = new Size(145, 22); buttonAdd.TabIndex = 1; buttonAdd.Text = "Добавить самолет"; buttonAdd.UseVisualStyleBackColor = true; @@ -145,33 +157,68 @@ // // buttonDelete // - buttonDelete.Location = new Point(38, 456); + buttonDelete.Location = new Point(38, 435); buttonDelete.Margin = new Padding(2); buttonDelete.Name = "buttonDelete"; - buttonDelete.Size = new Size(142, 30); + buttonDelete.Size = new Size(124, 22); buttonDelete.TabIndex = 3; buttonDelete.Text = "Удалить самолет"; buttonDelete.UseVisualStyleBackColor = true; buttonDelete.Click += buttonDelete_Click; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(2, 18); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(183, 24); + menuStrip.TabIndex = 7; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { сохранениеToolStripMenuItem, загрузкаToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(48, 20); + файлToolStripMenuItem.Text = "Файл"; + // + // сохранениеToolStripMenuItem + // + сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem"; + сохранениеToolStripMenuItem.Size = new Size(180, 22); + сохранениеToolStripMenuItem.Text = "Сохранение"; + сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // загрузкаToolStripMenuItem + // + загрузкаToolStripMenuItem.Name = "загрузкаToolStripMenuItem"; + загрузкаToolStripMenuItem.Size = new Size(180, 22); + загрузкаToolStripMenuItem.Text = "Загрузка"; + загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // // pictureBoxCollection // pictureBoxCollection.Dock = DockStyle.Fill; pictureBoxCollection.Location = new Point(0, 0); pictureBoxCollection.Margin = new Padding(2); pictureBoxCollection.Name = "pictureBoxCollection"; - pictureBoxCollection.Size = new Size(707, 570); + pictureBoxCollection.Size = new Size(619, 534); pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize; pictureBoxCollection.TabIndex = 6; pictureBoxCollection.TabStop = false; // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog1"; + // // FormAirplaneCollection // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(921, 570); + ClientSize = new Size(806, 534); Controls.Add(pictureBoxCollection); Controls.Add(groupBoxInstruments); + MainMenuStrip = menuStrip; Margin = new Padding(2); Name = "FormAirplaneCollection"; Text = "FormAirplaneCollection"; @@ -179,6 +226,8 @@ groupBoxInstruments.PerformLayout(); groupBoxSets.ResumeLayout(false); groupBoxSets.PerformLayout(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ResumeLayout(false); PerformLayout(); @@ -196,5 +245,11 @@ private ListBox listBoxStorages; private Button buttonAddInSet; private TextBox textBoxStorageName; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem сохранениеToolStripMenuItem; + private ToolStripMenuItem загрузкаToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs index 4821c61..40db2ed 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs @@ -30,6 +30,50 @@ namespace AirplaneWithRadar InitializeComponent(); _storage = new AirplanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.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 (_storage.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + ReloadObjects(); + } + /// /// Заполнение listBoxObjects /// @@ -90,7 +134,7 @@ namespace AirplaneWithRadar { return; } - if (MessageBox.Show($"Удалить объект { listBoxStorages.SelectedItem}?", + if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(listBoxStorages.SelectedItem.ToString() @@ -167,7 +211,6 @@ namespace AirplaneWithRadar { MessageBox.Show("Не удалось удалить объект"); } - } /// /// Обновление рисунка по набору diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.resx b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.resx index af32865..f53194e 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.resx +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 132, 17 + + + 271, 17 + \ No newline at end of file diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.Designer.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.Designer.cs index 852503f..134a209 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.Designer.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.Designer.cs @@ -135,7 +135,7 @@ // // panelYellow // - panelYellow.BackColor = Color.FromArgb(255, 255, 128); + panelYellow.BackColor = Color.LemonChiffon; panelYellow.Location = new Point(163, 20); panelYellow.Margin = new Padding(3, 2, 3, 2); panelYellow.Name = "panelYellow"; @@ -145,7 +145,7 @@ // // panelBlack // - panelBlack.BackColor = Color.FromArgb(64, 64, 64); + panelBlack.BackColor = Color.DimGray; panelBlack.Location = new Point(113, 59); panelBlack.Margin = new Padding(3, 2, 3, 2); panelBlack.Name = "panelBlack"; @@ -165,7 +165,7 @@ // // panelGray // - panelGray.BackColor = Color.DarkGray; + panelGray.BackColor = Color.Silver; panelGray.Location = new Point(64, 59); panelGray.Margin = new Padding(3, 2, 3, 2); panelGray.Name = "panelGray"; diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs index f794bf5..29caba0 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs @@ -108,7 +108,7 @@ namespace AirplaneWithRadar break; case "labelModifiedObject": _airplane = new DrawningAirplaneWithRadar((int)numericUpDownSpeed.Value, - (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxRadar.Checked, + (int)numericUpDownWeight.Value, Color.White, Color.DimGray, checkBoxRadar.Checked, checkBoxTank.Checked, checkBoxPin.Checked, pictureBoxObject.Width, pictureBoxObject.Height); break;