6 Commits

Author SHA1 Message Date
3a938f6349 , 2024-06-14 08:14:29 +04:00
75c7be6da3 Исправления 2024-06-12 19:58:09 +04:00
f58ea26eb5 lab 7/0 2024-06-12 17:36:43 +04:00
8322c1fcaf Лаб 7 2024-06-12 15:15:23 +04:00
e44a184f2e Lab 6 2024-05-22 23:13:09 +04:00
ef133ccb2c Лаба 6 правки 2024-05-22 23:03:52 +04:00
20 changed files with 717 additions and 89 deletions

View File

@@ -28,7 +28,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместитьв окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight))-1;
/// <summary>
/// Конструктор
/// </summary>
@@ -41,7 +41,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
@@ -81,11 +81,16 @@ public abstract class AbstractCompany
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
Drawningplane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
Drawningplane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
}
return bitmap;
}

View File

@@ -13,7 +13,12 @@ where T : class
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
@@ -39,4 +44,14 @@ where T : class
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// получение объектов коллекции по одному
/// </summary>
/// <returns></returns>
IEnumerable<T?> GetItems();
}

View File

@@ -1,4 +1,7 @@
namespace ProjectAiroplane.CollectionGenericObjects;
using ProjectAiroplane.Exceptions;
namespace ProjectAiroplane.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
@@ -11,7 +14,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary>
private int _maxCount;
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>
/// Конструктор
/// </summary>
@@ -19,37 +39,41 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
_collection = new();
}
public T? Get(int position)
public T Get(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0) return null;
return _collection[position];// индексатор
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (Count == _maxCount) return -1;
_collection.Add(obj);//метод
if (Count == _maxCount) throw new CollectionOverflowException();
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (Count == _maxCount) return -1;
if (position >= Count || position < 0) return -1;
_collection.Insert(position, obj);//метод
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position >= Count || position < 0) return null;
T obj = _collection[position];
_collection.RemoveAt(position);//метод
return obj;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T temp = _collection[position];
_collection.RemoveAt(position);
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; i++)
{
yield return _collection[i];
}
}
}

View File

@@ -1,4 +1,6 @@
namespace ProjectAiroplane.CollectionGenericObjects;
using ProjectAiroplane.Exceptions;
namespace ProjectAiroplane.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -12,8 +14,14 @@ where T : class
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -29,6 +37,9 @@ where T : class
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -40,7 +51,9 @@ where T : class
{
// TODO проверка позиции
if (position >= _collection.Length || position < 0)
{ return null; }
{ throw new PositionOutOfCollectionException(position); }
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
@@ -57,7 +70,7 @@ where T : class
index++;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
@@ -67,7 +80,9 @@ where T : class
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
{ return -1; }
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
@@ -93,7 +108,7 @@ where T : class
return position;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
@@ -101,10 +116,21 @@ where T : class
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
{ return null; }
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);//выброс1
T obj = _collection[position];
_collection[position] = null;
return obj;
}
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
}

View File

@@ -34,11 +34,12 @@ public class PlaneSharingService : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 2);
}
catch (Exception) { }
if (curWidth > 0)
curWidth--;
else

View File

@@ -1,10 +1,14 @@
namespace ProjectAiroplane.CollectionGenericObjects;
using ProjectAiroplane.Drawnings;
using ProjectAiroplane.Exceptions;
using System.Text;
namespace ProjectAiroplane.CollectionGenericObjects;
/// <summary>
/// класс-хранилище
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : Drawningplane
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@@ -64,4 +68,167 @@ public class StorageCollection<T>
return null;
}
}
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при
///сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count < 1)
{
throw new InvalidDataException("В хранилище отсутсвуют коллекции для сохранения");
}
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);
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);
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке
///данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_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);//////////////////CreateCollection
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningplane() is T airoplane)//////////////////////////////////////////////////////////////////CreateDrawningplane()
{
try
{
if (collection.Insert(airoplane) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
}
/// <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

@@ -15,15 +15,20 @@ public class DrawningAiroplane : Drawningplane
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="toplivbak">Признак наличия бака</param>
/// <param name="radar">Признак наличия радара</param>
public DrawningAiroplane(int speed, double weight, Color bodyColor, Color additionalColor, bool toplivbak, bool radar) : base(170,85)
public DrawningAiroplane(int speed, double weight, Color bodyColor, Color additionalColor, bool toplivbak, bool radar) : base(170, 85)
{
Entityplane = new EntityAiroplane(speed, weight, bodyColor, additionalColor, toplivbak, radar);
}
public DrawningAiroplane(EntityAiroplane airoplane) : base(170, 85)
{
Entityplane = new EntityAiroplane(airoplane.Speed, airoplane.Weight, airoplane.BodyColor, airoplane.AdditionalColor, airoplane.Toplivbak, airoplane.Radar);
}
public override void DrawTransport(Graphics g)
{
if (Entityplane == null || Entityplane is not EntityAiroplane airoplane|| !_startPosX.HasValue || !_startPosY.HasValue)
if (Entityplane == null || Entityplane is not EntityAiroplane airoplane || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
@@ -33,9 +38,9 @@ public class DrawningAiroplane : Drawningplane
Brush additionalBrush = new SolidBrush(airoplane.AdditionalColor);
if (airoplane.Toplivbak)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 65,_startPosY.Value + 20, 30, 15);
g.FillRectangle(additionalBrush, _startPosX.Value + 65, _startPosY.Value + 20, 30, 15);
}
//Радар
if (airoplane.Radar)
{

View File

@@ -73,6 +73,12 @@ public class Drawningplane
Entityplane = new Entityplane(speed, weight, bodyColor);
}
public Drawningplane(Entityplane airoplane) : this()
{
Entityplane = new Entityplane(airoplane.Speed, airoplane.Weight, airoplane.BodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>

View File

@@ -0,0 +1,50 @@
using ProjectAiroplane.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAiroplane.Drawnings;
public static class ExtentionDrawningPlane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static Drawningplane? CreateDrawningplane(this string info)
{
string[] strs = info.Split(_separatorForObject);
Entityplane? airoplane = EntityAiroplane.CreateEntityAiroplane(strs);
if (airoplane != null)
{
return new DrawningAiroplane((EntityAiroplane)airoplane);
}
airoplane = Entityplane.CreateEntityplane(strs);
if (airoplane != null)
{
return new Drawningplane(airoplane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningplane">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this Drawningplane drawningplane)
{
string[]? array = drawningplane?.Entityplane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -1,4 +1,6 @@
namespace ProjectAiroplane.Entities;
using System.Net.Sockets;
namespace ProjectAiroplane.Entities;
public class EntityAiroplane : Entityplane
{
/// <summary>
@@ -13,7 +15,7 @@ public class EntityAiroplane : Entityplane
/// Признак (опция) наличия радара
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Инициализация полей класса
/// </summary>
@@ -23,7 +25,7 @@ public class EntityAiroplane : Entityplane
/// <param name="additionalColor"></Дополнительный цвет>
/// <param name="toplivbak"></ Признак наличия бака>
/// <param name="radar"></Признак (опция) наличия радара>
public EntityAiroplane(int speed, double weight, Color bodyColor, Color additionalColor, bool toplivbak, bool radar) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
@@ -39,6 +41,28 @@ public class EntityAiroplane : Entityplane
{
AdditionalColor = color;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAiroplane), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Toplivbak.ToString(), Radar.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAiroplane? CreateEntityAiroplane(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAiroplane))
{
return null;
}
return new EntityAiroplane(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

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
@@ -52,5 +53,27 @@ public class Entityplane
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(Entityplane), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static Entityplane? CreateEntityplane(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(Entityplane))
{
return null;
}
return new Entityplane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectAiroplane.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace ProjectAiroplane.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
///
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }//обработка1
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace ProjectAiroplane.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -30,6 +30,7 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonAddPlane = new Button();
buttonGoToCheck = new Button();
buttonDelPlane = new Button();
maskedTextBox1 = new MaskedTextBox();
@@ -45,11 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
buttonAddPlane = new Button();
menuStrip1 = 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)pictureBox).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(859, 0);
groupBoxTools.Location = new Point(859, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(277, 680);
groupBoxTools.Size = new Size(277, 652);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@@ -79,9 +86,19 @@
panelCompanyTools.Size = new Size(268, 322);
panelCompanyTools.TabIndex = 9;
//
// buttonAddPlane
//
buttonAddPlane.Location = new Point(7, 14);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(252, 40);
buttonAddPlane.TabIndex = 1;
buttonAddPlane.Text = "Добавление самолёта";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += ButtonAddPlane_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(7, 189);
buttonGoToCheck.Location = new Point(4, 168);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(254, 42);
buttonGoToCheck.TabIndex = 5;
@@ -91,7 +108,7 @@
//
// buttonDelPlane
//
buttonDelPlane.Location = new Point(7, 140);
buttonDelPlane.Location = new Point(4, 119);
buttonDelPlane.Name = "buttonDelPlane";
buttonDelPlane.Size = new Size(254, 43);
buttonDelPlane.TabIndex = 4;
@@ -101,7 +118,7 @@
//
// maskedTextBox1
//
maskedTextBox1.Location = new Point(7, 107);
maskedTextBox1.Location = new Point(7, 74);
maskedTextBox1.Mask = "00";
maskedTextBox1.Name = "maskedTextBox1";
maskedTextBox1.Size = new Size(252, 27);
@@ -110,7 +127,7 @@
//
// buttonReFresh
//
buttonReFresh.Location = new Point(7, 237);
buttonReFresh.Location = new Point(4, 220);
buttonReFresh.Name = "buttonReFresh";
buttonReFresh.Size = new Size(252, 40);
buttonReFresh.TabIndex = 6;
@@ -225,21 +242,52 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(859, 680);
pictureBox.Size = new Size(859, 652);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// buttonAddPlane
// menuStrip1
//
buttonAddPlane.Location = new Point(7, 14);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(252, 40);
buttonAddPlane.TabIndex = 1;
buttonAddPlane.Text = "Добавление самолёта";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += ButtonAddPlane_Click;
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1136, 28);
menuStrip1.TabIndex = 2;
menuStrip1.Text = "menuStrip1";
//
// файл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_1;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click_1;
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormPlaneCollection
//
@@ -248,6 +296,8 @@
ClientSize = new Size(1136, 680);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormPlaneCollection";
Text = "Коллекция самолётов";
groupBoxTools.ResumeLayout(false);
@@ -256,7 +306,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -279,5 +332,11 @@
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private Button buttonAddPlane;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@@ -1,5 +1,7 @@
using ProjectAiroplane.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectAiroplane.CollectionGenericObjects;
using ProjectAiroplane.Drawnings;
using ProjectAiroplane.Exceptions;
using System.Windows.Forms;
namespace ProjectAiroplane;
@@ -14,15 +16,20 @@ public partial class FormPlaneCollection : Form
/// <summary>
/// Хранилище коллеций
/// </summary>
///
private readonly StorageCollection<Drawningplane> _storageCollection;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneCollection()
public FormPlaneCollection(ILogger<FormPlaneCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
/// Выбор компании
@@ -39,35 +46,50 @@ public partial class FormPlaneCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddPlane_Click(object sender, EventArgs e)//вопрос 2 ...........................................................
private void ButtonAddPlane_Click(object sender, EventArgs e)
{
FormPlanConfig form = new();
// TODO передать метод
form.Show();
form.AddEvent(SetPlane); //////////////////////////////
form.AddEvent(SetPlane);
}
/// <summary>
/// Добавление самолёта в коллекцию
/// </summary>
/// <param name="excavator"></param>
/// <param name="plane"></param>
private void SetPlane(Drawningplane? plane)
{
if (_company == null || plane == null)
try
{
return;
if (_company == null || plane == null)
{
return;
}
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + plane.GetDataForSave());
}
}
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
catch (ObjectNotFoundException) { MessageBox.Show("Не удалось добавить объект");//ловлю ошибку1
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Выход за границы коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -87,15 +109,23 @@ public partial class FormPlaneCollection : Form
{
return;
}
int pos = Convert.ToInt32(maskedTextBox1.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@@ -152,21 +182,30 @@ public partial class FormPlaneCollection : Form
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
try
{
collectionType = CollectionType.Massive;
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
else if (radioButtonList.Checked)
catch (Exception ex)
{
collectionType = CollectionType.List;
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
/// <summary>
@@ -185,12 +224,20 @@ public partial class FormPlaneCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
try
{
return;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
@@ -238,4 +285,44 @@ public partial class FormPlaneCollection : Form
RerfreshListBoxItems();
}
private void saveToolStripMenuItem_Click_1(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void loadToolStripMenuItem_Click_1(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

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="menuStrip1.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>153, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>323, 17</value>
</metadata>
</root>

View File

@@ -1,3 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace ProjectAiroplane
{
internal static class Program
@@ -11,7 +17,31 @@ namespace ProjectAiroplane
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormPlaneCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider servicesProvider = services.BuildServiceProvider();
Application.Run(servicesProvider.GetRequiredService<FormPlaneCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
}
}
}

View File

@@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +35,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}