ISEbd-12_Paramonova_I.A._LabWork06_Simple #19

Closed
ikswi wants to merge 2 commits from LabWork06.4 into LabWork05.1
13 changed files with 446 additions and 16 deletions

View File

@ -48,7 +48,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>

View File

@ -1,4 +1,6 @@
namespace ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@ -15,7 +17,7 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
@ -45,4 +47,15 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
}

View File

@ -19,7 +19,22 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
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;
/// <summary>
/// Конструктор
@ -57,4 +72,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return pos;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -14,8 +14,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@ -32,6 +36,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -105,4 +111,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,11 +1,14 @@
namespace ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
using System.Text;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningMilitaryAircraft
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -17,6 +20,20 @@ public class StorageCollection<T>
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@ -70,4 +87,145 @@ public class StorageCollection<T>
return _storages[name];
}
}
/// <summary>
/// Сохранение информации по военным самолётам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
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<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
Review

Записывать в файл можно сразу, без использования StringBuilder

Записывать в файл можно сразу, без использования StringBuilder
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;
}
/// <summary>
/// Загрузка информации по военным самолётам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
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<T>? collection = StorageCollection<T>.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?.CreateDrawningMilitaryAircraft() is T militaryAircraft)
{
if (collection.Insert(militaryAircraft) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
///
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -22,6 +22,22 @@ public class DrawningAirFighter : DrawningMilitaryAircraft
EntityMilitaryAircraft = new EntityAirFighter(speed, weight, bodyColor, additionalColor, wings, rockets);
}
/// <summary>
/// Конструктор
/// </summary>
public DrawningAirFighter(EntityAirFighter militaryAircraft) : base(110, 60)
{
EntityMilitaryAircraft = new EntityAirFighter(militaryAircraft.Speed, militaryAircraft.Weight, militaryAircraft.BodyColor, militaryAircraft.AdditionalColor, militaryAircraft.Wings, militaryAircraft.Rockets);
}
//public DrawningAirFighter(EntityMilitaryAircraft entityMilitaryAircraft) : base(110, 60)
Review

Закомментированного кода быть не должно

Закомментированного кода быть не должно
//{
// if (entityMilitaryAircraft != null)
// {
// EntityMilitaryAircraft = entityMilitaryAircraft;
// }
//}
public override void DrawTransport(Graphics g)
{
if (EntityMilitaryAircraft == null || EntityMilitaryAircraft is not EntityAirFighter airFighter || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@ -84,6 +84,15 @@ public class DrawningMilitaryAircraft
EntityMilitaryAircraft = new EntityMilitaryAircraft(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="militaryAircraft">Класс-сущность</param>
public DrawningMilitaryAircraft(EntityMilitaryAircraft militaryAircraft) : this()
{
EntityMilitaryAircraft = militaryAircraft;
}
/// <summary>
/// Конструктор для наследников
/// </summary>

View File

@ -0,0 +1,54 @@
using ProjectAirFighter.Entities;
namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtentionDrawningMilitaryAircraft
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningMilitaryAircraft? CreateDrawningMilitaryAircraft(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityMilitaryAircraft? militaryAircraft = EntityAirFighter.CreateEntityAirFighter(strs);
if (militaryAircraft != null)
{
return new DrawningAirFighter((EntityAirFighter)militaryAircraft);
}
militaryAircraft = EntityMilitaryAircraft.CreateEntityMilitaryAircraft(strs);
if (militaryAircraft != null)
{
return new DrawningMilitaryAircraft(militaryAircraft);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningMilitaryAircraft drawningMilitaryAircraft)
{
string[]? array = drawningMilitaryAircraft?.EntityMilitaryAircraft?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -22,4 +22,24 @@ public class EntityAirFighter : EntityMilitaryAircraft
Rockets = rockets;
Wings = wings;
}
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirFighter), Speed.ToString(), Weight.ToString(), BodyColor.Name, Wings.ToString(), Rockets.ToString(), AdditionalColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAirFighter? CreateEntityAirFighter(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityAirFighter))
{
return null;
}
return new EntityAirFighter(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@ -31,4 +31,28 @@ public class EntityMilitaryAircraft
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityMilitaryAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityMilitaryAircraft? CreateEntityMilitaryAircraft(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityMilitaryAircraft))
{
return null;
}
return new EntityMilitaryAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@ -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();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(744, 0);
groupBoxTools.Location = new Point(744, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(206, 667);
groupBoxTools.Size = new Size(206, 639);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -77,13 +84,13 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 357);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(200, 307);
panelCompanyTools.Size = new Size(200, 279);
panelCompanyTools.TabIndex = 10;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 252);
buttonRefresh.Location = new Point(0, 227);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(192, 49);
buttonRefresh.TabIndex = 7;
@ -94,7 +101,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 197);
buttonGoToCheck.Location = new Point(3, 178);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(192, 49);
buttonGoToCheck.TabIndex = 6;
@ -105,7 +112,7 @@
// buttonRemoveMilitaryAircraft
//
buttonRemoveMilitaryAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveMilitaryAircraft.Location = new Point(4, 142);
buttonRemoveMilitaryAircraft.Location = new Point(4, 129);
buttonRemoveMilitaryAircraft.Name = "buttonRemoveMilitaryAircraft";
buttonRemoveMilitaryAircraft.Size = new Size(191, 49);
buttonRemoveMilitaryAircraft.TabIndex = 5;
@ -127,7 +134,7 @@
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxPosition.Location = new Point(3, 109);
maskedTextBoxPosition.Location = new Point(3, 96);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(192, 27);
@ -241,12 +248,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(744, 667);
pictureBox.Size = new Size(744, 639);
pictureBox.TabIndex = 3;
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(950, 28);
menuStrip.TabIndex = 4;
menuStrip.Text = "menuStrip";
//
// файл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";
//
// FormMilitaryAircraftCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -254,6 +302,8 @@
ClientSize = new Size(950, 667);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMilitaryAircraftCollection";
Text = "Коллекция военных самолётов";
groupBoxTools.ResumeLayout(false);
@ -262,7 +312,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -285,5 +338,11 @@
private Button buttonCollectionAdd;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -226,4 +226,35 @@ public partial class FormMilitaryAircraftCollection : 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);
}
}
}
}

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 17</value>
</metadata>
</root>