PIBD-13_Fomichev_V.S._LabWork06_Simple_ #7

Closed
slavaxom9k wants to merge 3 commits from labwork06 into labwork05
13 changed files with 437 additions and 16 deletions

View File

@ -50,7 +50,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 AntiAircraftGun.CollectionGenereticObject;
using AntiAircraftGun.CollectionGenericObjects;
namespace AntiAircraftGun.CollectionGenereticObject;
/// <summary>
/// Интерфейс описания действий для набора хранимых данных
/// </summary>
@ -14,7 +16,7 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
@ -44,4 +46,14 @@ 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

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

View File

@ -1,4 +1,6 @@
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.CollectionGenericObjects;
using AntiAircraftGun.Drawnings;
namespace AntiAircraftGun.CollectionGenereticObject;
/// <summary>
@ -15,8 +17,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)
@ -33,6 +39,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -128,4 +136,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,4 +1,6 @@
using AntiAircraftGun.CollectionGenereticObject;
using AntiAircraftGun.Drawnings;
using System.Text;
namespace AntiAircraftGun.CollectionGenericObjects;
@ -7,7 +9,7 @@ namespace AntiAircraftGun.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningArmoredCar
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -18,6 +20,20 @@ public class StorageCollection<T>
/// Возвращение списка названий коллекций
/// </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>
/// Конструктор
@ -67,4 +83,129 @@ public class StorageCollection<T>
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter writer = new(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 = new(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
return false;
}
if (!line.Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
{
string[] record = line.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?.CreateDrawningArmoredCar() is T truck)
{
if (collection.Insert(truck) == -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

@ -21,6 +21,14 @@ public class DrawningAntiAircraftGun : DrawningArmoredCar
EntityAircraftGun = new EntityAntiAircraftGun(speed, weight, bodyColor, radar, tower, additionalColor);
}
/// <summary>
/// Конструктор для Extention
/// </summary>
/// <param name="airbus"></param>
public DrawningAntiAircraftGun(EntityAntiAircraftGun armoredCar) : base(130, 60)
{
EntityAircraftGun = new EntityAntiAircraftGun(armoredCar.Speed, armoredCar.Weight, armoredCar.BodyColor, armoredCar.Radar, armoredCar.Tower, armoredCar.AdditionalColor);
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>

View File

@ -92,6 +92,14 @@ public class DrawningArmoredCar
_drawningGunHeight = drawningGunHeight;
}
/// <summary>
/// Конструктор для Extention
/// </summary>
/// <param name="airplan"></param>
public DrawningArmoredCar(EntityArmoredCar armoredCar) : this()
{
EntityAircraftGun = new EntityArmoredCar(armoredCar.Speed, armoredCar.Weight, armoredCar.BodyColor);
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width"></param>

View File

@ -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;
/// <summary>
/// Расширение для класса EntityArmoredCar
/// </summary>
public static class ExtentionDrawningArmoredCar
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningArmoredCar? CreateDrawningArmoredCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityArmoredCar? armoredCar = EntityAntiAircraftGun.CreateEntityAntiAircraftGun(strs);
if (armoredCar != null)
{
return new DrawningAntiAircraftGun((EntityAntiAircraftGun)armoredCar);
}
armoredCar = EntityArmoredCar.CreateEntityArmoredCar(strs);
if (armoredCar != null)
{
return new DrawningArmoredCar(armoredCar);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="armoredCar">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningArmoredCar drawningArmoredCar)
{
string[]? array = drawningArmoredCar?.EntityAircraftGun?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -1,4 +1,6 @@
namespace AntiAircraftGun.Entities;
using AntiAircraftGun.Drawnings;
namespace AntiAircraftGun.Entities;
/// <summary>
/// Класс-сущность Зенитная установка
/// </summary>
@ -40,4 +42,28 @@ public class EntityAntiAircraftGun : EntityArmoredCar
Tower = tower;
AdditionalColor = additionalColor;
}
/// <summary>
/// Получение строк со значениями свойств продвинутого объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAntiAircraftGun), Speed.ToString(), Weight.ToString(), BodyColor.Name, Tower.ToString(), Radar.ToString(), AdditionalColor.Name};
}
/// <summary>
/// Создание продвинутого объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAntiAircraftGun? CreateEntityAntiAircraftGun(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAntiAircraftGun))
{
return null;
}
return new EntityAntiAircraftGun(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),Color.FromName(strs[6]));
}
}

View File

@ -41,4 +41,27 @@ public class EntityArmoredCar
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityArmoredCar), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityArmoredCar? CreateEntityArmoredCar(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]));
}
}

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();
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, 612);
groupBoxToools.TabIndex = 0;
groupBoxToools.TabStop = false;
groupBoxToools.Text = "Инструменты";
@ -239,19 +246,61 @@
// 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, 612);
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);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1267, 615);
ClientSize = new Size(1267, 636);
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;
}
}

View File

@ -242,5 +242,44 @@ public partial class FormArmoredCarCollection : 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="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root>