ISEbd-12 Avdeeva E.D. LabWork06 Simple #6

Closed
Ekaterina2357 wants to merge 2 commits from LabWork06 into LabWork05
13 changed files with 429 additions and 19 deletions

View File

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

View File

@ -21,7 +21,8 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
@ -51,4 +52,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

@ -25,7 +25,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@ -63,4 +65,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -21,8 +21,13 @@ 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)
@ -37,8 +42,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// конструктор
/// </summary>
@ -116,4 +124,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,4 +1,5 @@
using System;
using ProjectAirBomber.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -11,18 +12,32 @@ namespace ProjectAirBomber.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningBomber
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@ -79,4 +94,129 @@ public class StorageCollection<T>
return null;
}
}
/// <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)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
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 reader = File.OpenText(filename);
string? str = reader.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string? strs = "";
while ((strs = reader.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?.CreateDrawningBomber() is T bomber)
{
if (collection.Insert(bomber) == -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

@ -16,11 +16,21 @@ public class DrawningAirBomber : DrawningBomber
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="fuelTanks">Признак наличия топливных баков</param>
public DrawningAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(150, 145)
public DrawningAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(145, 148)
{
EntityBomber = new EntityAirBomber(speed, weight, bodyColor, additionalColor, bombs, fuelTanks);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="bomber">Класс-сущность</param>
public DrawningAirBomber(EntityBomber bomber) : base(140, 90)
{
EntityBomber = bomber;
}
public override void DrawTransport(Graphics g)
{

View File

@ -79,7 +79,6 @@ public class DrawningBomber
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
@ -92,6 +91,15 @@ public class DrawningBomber
EntityBomber = new EntityBomber(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="bomber">Класс-сущность</param>
public DrawningBomber(EntityBomber bomber) : this()
{
EntityBomber = bomber;
}
/// <summary>
/// Конструктор для наследников
/// </summary>

View File

@ -0,0 +1,61 @@
using ProjectAirBomber.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace ProjectAirBomber.Drawnings;
/// <summary>
/// Расширение для класса EntityBomber
/// </summary>
public static class ExtentionDrawningBomber
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningBomber? CreateDrawningBomber(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityBomber? bomber = EntityAirBomber.CreateEntityAirBomber(strs);
if (bomber != null)
{
return new DrawningAirBomber(bomber);
}
bomber = EntityBomber.CreateEntityBomber(strs);
if (bomber != null)
{
return new DrawningBomber(bomber);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningBomber">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBomber drawningBomber)
{
string[]? array = drawningBomber?.EntityBomber?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -36,7 +36,29 @@ public class EntityAirBomber : EntityBomber
/// </summary>
public bool FuelTanks { get; private set; }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirBomber), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Bombs.ToString(), FuelTanks.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAirBomber? CreateEntityAirBomber(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAirBomber))
{
return null;
}
return new EntityAirBomber(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

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

View File

@ -32,7 +32,6 @@
panelCompanyTools = new Panel();
maskedTextBox = new MaskedTextBox();
buttonAddBomber = new Button();
buttonAddAirBomber = new Button();
buttonRefresh = new Button();
buttonDelBomber = new Button();
buttonGoToCheck = new Button();
@ -47,11 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox1 = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
panelCompanyTools.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -61,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(758, 0);
groupBoxTools.Location = new Point(758, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(251, 683);
groupBoxTools.Size = new Size(251, 655);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -72,7 +77,6 @@
//
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonAddBomber);
panelCompanyTools.Controls.Add(buttonAddAirBomber);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonDelBomber);
panelCompanyTools.Controls.Add(buttonGoToCheck);
@ -95,7 +99,7 @@
// buttonAddBomber
//
buttonAddBomber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBomber.Location = new Point(3, 4);
buttonAddBomber.Location = new Point(3, 3);
buttonAddBomber.Name = "buttonAddBomber";
buttonAddBomber.Size = new Size(224, 51);
buttonAddBomber.TabIndex = 1;
@ -243,12 +247,54 @@
// pictureBox1
//
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.Location = new Point(0, 0);
pictureBox1.Location = new Point(0, 28);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new Size(758, 683);
pictureBox1.Size = new Size(758, 655);
pictureBox1.TabIndex = 1;
pictureBox1.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(1009, 28);
menuStrip.TabIndex = 2;
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;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormBomberCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -256,6 +302,8 @@
ClientSize = new Size(1009, 683);
Controls.Add(pictureBox1);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormBomberCollection";
Text = "Коллекция бомбардировщиков";
groupBoxTools.ResumeLayout(false);
@ -264,7 +312,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -272,7 +323,6 @@
private GroupBox groupBoxTools;
private Button buttonAddBomber;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddAirBomber;
private PictureBox pictureBox1;
private Button buttonDelBomber;
private MaskedTextBox maskedTextBox;
@ -288,5 +338,11 @@
private Button buttonCollectionDel;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -295,7 +295,7 @@ public partial class FormBomberCollection : Form
return;
}
ICollectionGenericObjects<DrawningBomber>? collection = _storageCollection [listBoxCollection.SelectedItem.ToString() ?? string.Empty];
ICollectionGenericObjects<DrawningBomber>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
@ -312,5 +312,46 @@ public partial class FormBomberCollection : Form
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>315, 17</value>
</metadata>
</root>