Pibd-13 Kadyshev_M.I. LabWork07 Base #7

Closed
nezui wants to merge 1 commits from LabWork07 into LabWork06
14 changed files with 300 additions and 112 deletions

View File

@ -1,16 +0,0 @@
using ProjectAirFighter.Drawning;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter;
public class AdNum<T>
where T : DrawningAirFighter
{
public void Nothing(){
}
}

View File

@ -37,7 +37,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, которые можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)) + 1;
/// <summary>
/// Конструктор

View File

@ -1,4 +1,5 @@
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -40,7 +41,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
if (value > 0)
{
_maxCount = value;
_maxCount = value ;
}
}
}
@ -57,19 +58,19 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
//проверка позиции
if (position >= Count || position < 0)
{
return null;
}
throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
//проверка, что не превышено максимальное количество элементов
if(Count + 1 > _maxCount)
{
return -1;
}
throw new CollectionOverflowException(Count);
//вставка в конец набора
_collection.Add(obj);
return Count;
@ -77,11 +78,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Insert(T obj, int position)
{
if (Count + 1 > _maxCount)
throw new CollectionOverflowException(Count);
//проверка позиции
if (position < 0 || position >= Count)
{
return -1;
}
throw new PositionOutOfCollectionException(position);
//вставка по позиции
_collection.Insert(position,obj);
return 1;
@ -90,9 +92,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Remove(int position)
{
if (position < 0 || position >= Count)
{
return null;
}
throw new PositionOutOfCollectionException(position);
T? temp = _collection[position];
_collection.RemoveAt(position);
return temp;

View File

@ -1,5 +1,6 @@
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -56,11 +57,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
if (position < 0 || position > Count)
throw new PositionOutOfCollectionException(position);
if (position >= _collection.Length && _collection[position] == null)
throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
@ -73,13 +76,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
return -1;
if (position < 0 || position > Count)
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
@ -109,17 +112,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
temp--;
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position < 0 || position >= Count)
return null;
if (position < 0 || position > Count)
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
return null;
throw new ObjectNotFoundException(position);
}
T? temp = _collection[position];

View File

@ -1,5 +1,6 @@
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.Drawning;
using ProjectAirFighter.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -100,10 +101,10 @@ public class StorageCollection<T>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
return false;
throw new Exception("В хранилище отсутсвуют коллекции для сохранения");
Review

Требовалось заменить класс Exception на его более подходящих наследников

Требовалось заменить класс Exception на его более подходящих наследников
if (File.Exists(filename))
File.Delete(filename);
@ -138,18 +139,18 @@ public class StorageCollection<T>
sw.Write(_separatorItems);
}
}
return true;
}
/// <summary>
/// Загрузка информации по самолетам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не существует");
}
using (FileStream fs = new(filename, FileMode.Open))
@ -159,12 +160,12 @@ public class StorageCollection<T>
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new Exception("В файле нет данных");
}
if (!str.Equals(_collectionKey))
{
return false;
throw new Exception("В файле неверные данные");
}
_storages.Clear();
@ -180,7 +181,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -190,14 +191,24 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningWarPlane() is T warPlane)
{
if (collection.Insert(warPlane) == -1)
return false;
try
{
if (collection.Insert(warPlane) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch(CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
/// <summary>

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку преполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: count " + 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,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку преполнения коллекции
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
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,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.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

@ -143,7 +143,7 @@
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
@ -168,7 +168,7 @@
buttonCollectionRemove.TabIndex = 6;
buttonCollectionRemove.Text = "Удалить коллекцию";
buttonCollectionRemove.UseVisualStyleBackColor = true;
buttonCollectionRemove.Click += buttonCollectionRemove_Click;
buttonCollectionRemove.Click += ButtonCollectionRemove_Click;
//
// listBoxCollection
//
@ -187,7 +187,7 @@
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += buttonCollectionAdd_Click;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
@ -270,7 +270,7 @@
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
@ -278,7 +278,7 @@
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click_1;
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click_1;
//
// saveFileDialog
//

View File

@ -1,15 +1,9 @@
using ProjectAirFighter.CollectionGenericObject;
using Microsoft.Extensions.Logging;
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawning;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter;
@ -25,13 +19,19 @@ public partial class FormWarPlaneCollection : Form
/// </summary>
private AbstractCompany? _company;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormWarPlaneCollection()
public FormWarPlaneCollection(ILogger<FormWarPlaneCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@ -60,15 +60,27 @@ public partial class FormWarPlaneCollection : Form
{
return;
}
if (_company + warPlane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
try {
if (_company + warPlane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен: " + warPlane.GetDataForSave());
}
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -87,15 +99,24 @@ public partial class FormWarPlaneCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
try {
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален на позиции: " + pos);
}
}
else
catch(ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch(PositionOutOfCollectionException ex) {
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
@ -110,12 +131,25 @@ public partial class FormWarPlaneCollection : Form
int counter = 100;
while (warPlane == null)
{
warPlane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
try {
warPlane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
if (warPlane == null)
@ -144,13 +178,15 @@ public partial class FormWarPlaneCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCollectionAdd_Click(object sender, EventArgs e)
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try {
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@ -162,7 +198,13 @@ public partial class FormWarPlaneCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
_logger.LogInformation("Коллекция добавлена: " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Massege}", ex.Message);
}
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
@ -184,27 +226,32 @@ public partial class FormWarPlaneCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCollectionRemove_Click(object sender, EventArgs e)
private void ButtonCollectionRemove_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
try {
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>
/// Создать компанию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCompany_Click(object sender, EventArgs e)
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
@ -237,18 +284,21 @@ public partial class FormWarPlaneCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filname}", saveFileDialog.FileName);
}
else
{
MessageBox.Show("Не сохраненилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
catch(Exception ex) {
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -259,19 +309,24 @@ public partial class FormWarPlaneCollection : Form
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click_1(object sender, EventArgs e)
private void LoadToolStripMenuItem_Click_1(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filname}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

View File

@ -339,7 +339,7 @@
Controls.Add(groupBoxConfig);
Margin = new Padding(3, 2, 3, 2);
Name = "FormWarPlaneConfig";
Text = "Создание объекта";
Text = "98";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColor.ResumeLayout(false);

View File

@ -1,17 +1,42 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirFighter
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormWarPlaneCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormWarPlaneCollection>());
}
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<FormWarPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(pathNeed)
.AddJsonFile("serilog.json")
.Build())
.CreateLogger());
});
}
}
}
}

View File

@ -8,6 +8,15 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

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