7 лабораторная работа

This commit is contained in:
Ekaterina23578 2024-05-26 16:48:33 +04:00
parent b4c1796f23
commit eb2c515645
13 changed files with 336 additions and 138 deletions

BIN
ProjectAirBomber.zip Normal file

Binary file not shown.

View File

@ -1,4 +1,5 @@
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -39,10 +40,11 @@ public abstract class AbstractCompany
/// </summary>
protected ICollectionGenericObjects<DrawningBomber>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@ -101,10 +103,14 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningBomber? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException) { }
}
return bitmap;
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectAirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -39,33 +40,35 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= Count) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T? obj)
{
if (Count == _maxCount) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count - 1;
return Count;
}
public int Insert(T? obj, int position)
{
if (Count == _maxCount) return -1;
if (position < 0 || position >= Count) return -1;
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)
{
if (position < 0 || position >= Count) return null;
T? obj = _collection[position];
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)

View File

@ -1,4 +1,5 @@
using System;
using ProjectAirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -57,17 +58,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position > Count)
{
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)
{
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -76,54 +74,56 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
}
public int Insert(T obj, int position)
{
if (position < 0 || position > Count)
{
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T? obj, int position)
{
if (position >= _collection.Length || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
for (int i = position + 1; i < Count; i++)
int emptyPosition = position + 1;
while (emptyPosition < _collection.Length)
{
if (_collection[i] == null)
if (_collection[emptyPosition] == null)
{
_collection[i] = obj;
return position;
_collection[emptyPosition] = obj;
return emptyPosition;
}
++emptyPosition;
}
for (int i = position - 1; i >= 0; i--)
emptyPosition = position - 1;
while (emptyPosition >= 0)
{
if (_collection[i] == null)
if (_collection[emptyPosition] == null)
{
_collection[i] = obj;
return position;
_collection[emptyPosition] = obj;
return emptyPosition;
}
--emptyPosition;
}
return -1;
throw new CollectionOverflowException(_collection.Length);
}
public T? Remove(int position)
{
if (position < 0 || position > Count || _collection[position] == null)
{
return null;
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T temp = _collection[position];
_collection[position] = null;
return temp;
}
T? obj = _collection[position];
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{

View File

@ -1,4 +1,5 @@
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -99,12 +100,12 @@ 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 Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -142,31 +143,28 @@ public class StorageCollection<T>
writer.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 StreamReader reader = File.OpenText(filename);
string? str = reader.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string? strs = "";
@ -184,7 +182,7 @@ public class StorageCollection<T>
if (collection == null)
{
return false;
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@ -192,25 +190,30 @@ public class StorageCollection<T>
foreach (string elem in set)
{
if (elem?.CreateDrawningBomber() is T bomber)
{
try
{
if (collection.Insert(bomber) == -1)
{
return false;
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{

View File

@ -1,4 +1,5 @@
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -33,6 +34,7 @@ public class WarPlaneService : AbstractCompany
}
protected override void SetObjectsPosition()
{
{
if (_collection == null) return;
int width = _pictureWidth / _placeSizeWidth;
@ -43,14 +45,15 @@ public class WarPlaneService : AbstractCompany
for (int i = 0; i < _collection.Count; i++)
{
DrawningBomber? _bomber = _collection.Get(i);
if (_bomber != null)
try
{
DrawningBomber? _bomber = _collection.Get(i);
if (_bomber.SetPictureSize(_pictureWidth, _pictureHeight))
{
_bomber.SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 15);
}
}
catch (ObjectNotFoundException) { }
curWidth--;
if (curWidth < 0)
{
@ -63,4 +66,6 @@ public class WarPlaneService : AbstractCompany
}
}
}
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.Exceptions;
[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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.Exceptions;
[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,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.Exceptions;
[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;
@ -27,13 +29,20 @@ 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;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@ -121,16 +130,25 @@ public partial class FormBomberCollection : Form
return;
}
try
{
if (_company + bomber != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox1.Image = _company.Show();
_logger.LogInformation("Объект добавлен");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
catch (CollectionOverflowException ex)
{
MessageBox.Show("Коллекция переполнена");
_logger.LogError("Ошибка: " + ex.Message);
}
}
/// <summary>
/// удаление объекта
@ -144,21 +162,25 @@ public partial class FormBomberCollection : Form
return;
}
if (MessageBox.Show("Удалить объект", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox1.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -177,6 +199,8 @@ public partial class FormBomberCollection : Form
DrawningBomber? bomber = null;
int counter = 100;
try
{
while (bomber == null)
{
bomber = _company.GetRandomObject();
@ -186,18 +210,22 @@ public partial class FormBomberCollection : Form
break;
}
}
if (bomber == null)
{
return;
}
FormAirBomber form = new()
{
SetBomber = bomber
};
form.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Перерисовка коллекции
@ -224,10 +252,12 @@ public partial class FormBomberCollection : Form
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@ -237,9 +267,15 @@ public partial class FormBomberCollection : Form
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
RerfreshListBoxItems();
}
/// <summary>
@ -322,13 +358,16 @@ 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);
}
}
}
@ -342,14 +381,18 @@ public partial class FormBomberCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirBomber
{
internal static class Program
@ -11,7 +16,36 @@ namespace ProjectAirBomber
// 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>());
}
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
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}serilog.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,21 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.LoggerConfiguration.ConditionExtensions" Version="1.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

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\""
}
}
}