This commit is contained in:
Anna 2023-12-15 23:53:20 +04:00
parent 45f44fe42f
commit 7a60c03c4a
5 changed files with 281 additions and 3 deletions

View File

@ -0,0 +1,61 @@
using Airbus_Base.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityAirplane
/// </summary>
public static class ExtentionDrawningAirplane
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
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 == 6)
{
return new DrawningAirbus(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAirplane">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
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 EntityAirbus airBus)
{
return str;
}
return
$"{str}{separatorForObject}{airBus.AdditionalColor.Name}{separatorForObject}{airBus.AdditionalEngine}" +
$"{separatorForObject}{airBus.AdditionalPassengerCompartment}";
}
}
}

View File

@ -1,4 +1,6 @@
namespace Airbus_Base
using System.Windows.Forms;
namespace Airbus_Base
{
partial class FormAirplaneCollection
{
@ -41,9 +43,16 @@
this.maskedTextBoxNumber = new System.Windows.Forms.TextBox();
this.LabelTools = new System.Windows.Forms.Label();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.menuStrip = new MenuStrip();
this.FileToolStripMenuItem = new ToolStripMenuItem();
this.SaveToolStripMenuItem = new ToolStripMenuItem();
this.LoadToolStripMenuItem = new ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.toolsPanel.SuspendLayout();
this.panelSets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// toolsPanel
@ -165,12 +174,52 @@
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(1, -2);
this.pictureBoxCollection.Location = new System.Drawing.Point(1, 31);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(676, 451);
this.pictureBoxCollection.Size = new System.Drawing.Size(676, 471);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// menuStrip1
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(882, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(59, 24);
FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(224, 26);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(224, 26);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormAirplaneCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
@ -178,6 +227,8 @@
this.ClientSize = new System.Drawing.Size(900, 450);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.toolsPanel);
this.Controls.Add(menuStrip);
this.MainMenuStrip = menuStrip;
this.Name = "FormAirplaneCollection";
this.Text = "FormAirplaneCollection";
this.toolsPanel.ResumeLayout(false);
@ -185,10 +236,18 @@
this.panelSets.ResumeLayout(false);
this.panelSets.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
PerformLayout();
}
private void LoadToolStripMenuItem_Click1(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
private Panel toolsPanel;
@ -204,5 +263,11 @@
private Button ButtonRefreshCollection;
private ListBox listBoxObjects;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -193,5 +193,49 @@ namespace Airbus_Base
}
pictureBoxCollection.Image = obj.ShowTheAirplanes();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storage.Keys)
{
listBoxObjects.Items.Add(collection);
}
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -33,6 +33,19 @@ namespace Airbus_Base.Generics
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
@ -44,6 +57,97 @@ namespace Airbus_Base.Generics
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Сохранение информации по самолётам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, TheAirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>> record in _airplaneStorages)
{
StringBuilder records = new();
foreach (DrawningAirplane? elem in record.Value.GetTheAirplanes)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
string toWrite = $"AirplaneStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter sw = new(filename))
{
foreach (var str in strs)
{
sw.WriteLine(str);
}
}
return true;
}
/// <summary>
/// Загрузка информации по автобусам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].StartsWith("AirplaneStorage"))
{
return false;
}
_airplaneStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
TheAirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane> 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);
str = sr.ReadLine();
} while (str != null);
}
return true;
}
/// <summary>
/// Добавление набора

View File

@ -17,6 +17,10 @@ namespace Airbus_Base.Generics
where T : DrawningAirplane
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTheAirplanes => _collection.GetTheAirplanes();
/// <summary>
/// Ширина окна прорисовки
/// </summary>