Pibd-14 Aliulov_S.R. LabWork07 Simple #10

Closed
SAliulovq wants to merge 1 commits from LabWork07 into LabWork06
12 changed files with 302 additions and 138 deletions

View File

@ -1,4 +1,5 @@
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
namespace ProjectAirBomber.CollectionGenericObjects;
@ -32,18 +33,18 @@ public abstract class AbstractCompany
/// </summary>
protected ICollectionGenericObjects<DrawningBomber>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция поездов</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBomber> collection)
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция поездов</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBomber> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
@ -83,31 +84,37 @@ public abstract class AbstractCompany
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningBomber? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningBomber? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
return bitmap;
}
}
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов

View File

@ -1,5 +1,6 @@
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Entities;
using ProjectAirBomber.Exceptions;
using System;
namespace ProjectAirBomber.CollectionGenericObjects;
@ -9,56 +10,63 @@ namespace ProjectAirBomber.CollectionGenericObjects;
/// </summary>
public class BomberHungarService : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public BomberHungarService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBomber> collection) : base(picWidth, picHeight, collection)
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public BomberHungarService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBomber> collection) : base(picWidth, picHeight, collection)
{
}
/// <summary>
/// Вывод заднего фона
/// Отрисовка хранилища
/// </summary>
/// <param name="g"></param>
///
/// <param name="g">Графика</param>
int pamat_i = 0;
int pamat_j = 0;
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black, 2);
for (int i = 0; i < _pictureWidth / _placeSizeWidth + 1; i++)
Pen pen = new(Color.Black, 4);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
pamat_i = i;
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
pamat_j = j;
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * j));
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
}
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
}
}
/// <summary>
/// Установка объекта в Ангар
/// </summary>
protected override void SetObjectsPosition()
{
int n = 0;
for (int i = _pictureWidth / _placeSizeWidth; i > 0; i--)
int currentIndex = 0;
for (int j = pamat_j; j >= 0; j--)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
for (int i = pamat_i; i >= 0; i--)
{
DrawningBomber? drawningBomber = _collection?.Get(n);
n++;
if (drawningBomber != null)
try
{
drawningBomber.SetPictureSize(_pictureWidth, _pictureHeight);
drawningBomber.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
if (_collection?.Get(currentIndex) != null)
{
_collection.Get(currentIndex)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(currentIndex)?.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
catch (ObjectNotFoundException)
{
}
currentIndex++;
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectAirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -50,25 +51,26 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Get(int position)
{
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position];
}
public int Insert(T obj)
{
if (Count + 1 > _maxCount) return -1;
if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count + 1 > _maxCount) return -1;
if (position < 0 || position > Count) return -1;
if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return 1;
return position;
}
public T? Remove(int position)
{
if (position < 0 || position > Count) return null;
if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
T? temp = _collection[position];
_collection.RemoveAt(position);
return temp;
@ -81,4 +83,4 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
}
}

View File

@ -1,6 +1,6 @@
using System.Runtime.Remoting;
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
namespace ProjectAirBomber.CollectionGenericObjects;
/// <summary>
@ -52,12 +52,9 @@ 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 (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
@ -72,20 +69,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
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)
{
bool pushed = false;
@ -114,7 +108,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (!pushed)
{
return position;
throw new CollectionOverflowException(Count);
}
}
@ -123,21 +117,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position;
}
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;
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)

View File

@ -1,4 +1,6 @@
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
using System.Data;
using System.Text;
namespace ProjectAirBomber.CollectionGenericObjects;
@ -88,12 +90,11 @@ public class StorageCollection<T>
/// Сохранение информации по самолётам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -133,21 +134,18 @@ public class StorageCollection<T>
}
writer.Write(sb);
}
}
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 FileNotFoundException($"{filename} не существует");
}
using (StreamReader fs = File.OpenText(filename))
@ -155,11 +153,11 @@ public class StorageCollection<T>
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new FileFormatException("Файл не подходит");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new IOException("В файле неверные данные");
}
_storages.Clear();
string strs = "";
@ -174,7 +172,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@ -182,15 +180,21 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningBomber() is T bomber)
{
if (collection.Insert(bomber) == -1)
try
{
return false;
if (collection.Insert(bomber) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new DataException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
@ -208,4 +212,4 @@ public class StorageCollection<T>
_ => null,
};
}
}
}

View File

@ -0,0 +1,18 @@

using System.Runtime.Serialization;
namespace ProjectAirBomber.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,17 @@

using System.Runtime.Serialization;
namespace ProjectAirBomber.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,17 @@

using System.Runtime.Serialization;
namespace ProjectAirBomber.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

@ -1,5 +1,7 @@
using ProjectAirBomber.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectAirBomber.CollectionGenericObjects;
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -29,15 +31,22 @@ public partial class FormBomberCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormBomberCollection()
public FormBomberCollection(ILogger<FormBomberCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
/// </summary>
@ -71,14 +80,17 @@ public partial class FormBomberCollection : Form
return;
}
if (_company + bomber != -1)
try
{
int addingObject = (_company + bomber);
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {bomber.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError($"Не удалось добавить объект: {ex.Message}");
}
}
@ -92,6 +104,7 @@ public partial class FormBomberCollection : Form
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
_logger.LogError("Удаление объекта из несуществующей коллекции");
return;
}
@ -101,14 +114,22 @@ public partial class FormBomberCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
object decrementObject = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show();
}
else
catch (ObjectNotFoundException)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Объект не найден");
_logger.LogError($"Удаление не найденного объекта в позиции {pos} ");
}
catch (PositionOutOfCollectionException)
{
MessageBox.Show("Удаление вне рамках коллекции");
_logger.LogError($"Удаление объекта за пределами коллекции {pos} ");
}
}
@ -124,28 +145,33 @@ public partial class FormBomberCollection : Form
return;
}
DrawningBomber? bomber = null;
int counter = 100;
while (bomber == null)
try
{
bomber = _company.GetRandomObject();
counter--;
if (counter <= 0)
DrawningBomber? bomber = null;
int counter = 100;
while (bomber == null)
{
break;
bomber = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (bomber == null)
{
return;
}
FormAirBomber form = new()
{
SetBomber = bomber
};
form.ShowDialog();
}
if (bomber == null)
catch (ObjectNotFoundException)
{
return;
_logger.LogError("Ошибка при передаче объекта на FormAirFighter");
}
FormAirBomber form = new()
{
SetBomber = bomber
};
form.ShowDialog();
}
/// <summary>
@ -226,6 +252,7 @@ public partial class FormBomberCollection : Form
}
}
}
/// <summary>
/// Создание компании
/// </summary>
@ -264,17 +291,21 @@ public partial class FormBomberCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
@ -284,16 +315,17 @@ public partial class FormBomberCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
RerfreshListBoxItems();
}
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

@ -1,17 +1,45 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Serilog;
using Microsoft.Extensions.Logging;
namespace ProjectAirBomber
{
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 FormBomberCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormBomberCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBomberCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -8,6 +8,20 @@
<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.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="4.0.0" />
<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 +37,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "AirBomber"
}
}
}