lab 7 done
This commit is contained in:
parent
6c9b0e2584
commit
60c0a67594
@ -1,4 +1,5 @@
|
||||
using ProjectAirFighter.Drawnings;
|
||||
using ProjectAirFighter.Exceptions;
|
||||
|
||||
namespace ProjectAirFighter.CollectionGenericObjects;
|
||||
|
||||
@ -101,8 +102,13 @@ public abstract class AbstractCompany
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawningWarPlane? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawningWarPlane? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException) { };
|
||||
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectAirFighter.Drawnings;
|
||||
using ProjectAirFighter.Exceptions;
|
||||
|
||||
namespace ProjectAirFighter.CollectionGenericObjects;
|
||||
|
||||
@ -43,8 +44,13 @@ public class Hangar : AbstractCompany
|
||||
{
|
||||
for (int x = ((valPlaceX - 1) * _placeSizeWidth) + 10; x >= 0; x -= _placeSizeWidth)
|
||||
{
|
||||
_collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection?.Get(counter)?.SetPosition(x, y);
|
||||
try
|
||||
{
|
||||
_collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection?.Get(counter)?.SetPosition(x, y);
|
||||
}
|
||||
catch (ObjectNotFoundException) { }
|
||||
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,6 @@
|
||||
|
||||
using ProjectAirFighter.Exceptions;
|
||||
|
||||
namespace ProjectAirFighter.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
@ -44,40 +46,44 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= 0 && position < Count)
|
||||
if (position < 0 && position > Count)
|
||||
{
|
||||
return _collection[position];
|
||||
throw new PositionOutOfCollectionException();
|
||||
}
|
||||
else
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
return null;
|
||||
throw new ObjectNotFoundException();
|
||||
}
|
||||
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count == _maxCount) { return -1; }
|
||||
if (Count == _maxCount) { throw new CollectionOverflowException(); }
|
||||
_collection.Add(obj);
|
||||
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position < 0 || position >= Count || Count == _maxCount)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
|
||||
if (Count == _maxCount) throw new CollectionOverflowException();
|
||||
_collection.Insert(position, obj);
|
||||
|
||||
return position;
|
||||
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position >= Count || position < 0) return null;
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
|
||||
if (obj == null) throw new ObjectNotFoundException();
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,6 @@
|
||||
|
||||
using ProjectAirFighter.Exceptions;
|
||||
|
||||
namespace ProjectAirFighter.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
@ -50,12 +52,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= 0 && position < Count)
|
||||
if (position < 0 && position >= Count)
|
||||
{
|
||||
return _collection[position];
|
||||
throw new PositionOutOfCollectionException();
|
||||
}
|
||||
|
||||
return null;
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException();
|
||||
}
|
||||
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
|
||||
@ -68,8 +75,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return -1;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
@ -93,17 +101,26 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
throw new CollectionOverflowException(_collection.Length);
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return null;
|
||||
throw new PositionOutOfCollectionException();
|
||||
}
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException();
|
||||
}
|
||||
|
||||
T obj = _collection[position];
|
||||
_collection[position] = null;
|
||||
|
||||
if (obj == null) { throw new ObjectNotFoundException(); }
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectAirFighter.Drawnings;
|
||||
using ProjectAirFighter.Exceptions;
|
||||
using System.Text;
|
||||
|
||||
namespace ProjectAirFighter.CollectionGenericObjects;
|
||||
@ -94,13 +95,12 @@ public class StorageCollection<T>
|
||||
/// <summary>
|
||||
/// Сохранение информации по кораблям в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
/// <param name="filename">Путь и имя файла</param
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
@ -136,7 +136,6 @@ public class StorageCollection<T>
|
||||
sb.Clear();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@ -144,20 +143,18 @@ public class StorageCollection<T>
|
||||
/// Загрузка информации по кораблям в хранилище из файла
|
||||
/// </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("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader sr = new StreamReader(filename))
|
||||
{
|
||||
string? str;
|
||||
str = sr.ReadLine();
|
||||
if (str != _collectionKey.ToString())
|
||||
return false;
|
||||
if (str != _collectionKey.ToString()) throw new FormatException("В файле неверные данные");
|
||||
_storages.Clear();
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
{
|
||||
@ -170,7 +167,7 @@ public class StorageCollection<T>
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
@ -180,14 +177,20 @@ public class StorageCollection<T>
|
||||
{
|
||||
if (elem?.CreateDrawningPlane() is T ship)
|
||||
{
|
||||
if (collection.Insert(ship) == -1)
|
||||
return false;
|
||||
try
|
||||
{
|
||||
if (collection.Insert(ship) == -1) throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -0,0 +1,20 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectAirFighter.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) { }
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
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) { }
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
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) { }
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
using ProjectAirFighter.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectAirFighter.CollectionGenericObjects;
|
||||
using ProjectAirFighter.Drawnings;
|
||||
using ProjectAirFighter.Exceptions;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ProjectAirFighter;
|
||||
@ -19,13 +21,19 @@ public partial class FormWarPlaneCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormWarPlaneCollection()
|
||||
public FormWarPlaneCollection(ILogger<FormWarPlaneCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -49,14 +57,22 @@ public partial class FormWarPlaneCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + plane != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (_company + plane != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show("Ошибка переполнения коллекции");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -84,15 +100,30 @@ public partial class FormWarPlaneCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
if (_company - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удаление объекта по индексу {pos}", pos);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogInformation("Не удалось удалить объект из коллекции по индексу {pos}", pos);
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (ObjectNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show("Ошибка: отсутствует объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (PositionOutOfCollectionException ex)
|
||||
{
|
||||
MessageBox.Show("Ошибка: неправильная позиция");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -157,6 +188,7 @@ public partial class FormWarPlaneCollection : Form
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
|
||||
return;
|
||||
}
|
||||
|
||||
@ -171,6 +203,7 @@ public partial class FormWarPlaneCollection : Form
|
||||
}
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
@ -191,6 +224,7 @@ public partial class FormWarPlaneCollection : Form
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
@ -251,13 +285,16 @@ public partial class FormWarPlaneCollection : 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);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -272,14 +309,17 @@ public partial class FormWarPlaneCollection : Form
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
RerfreshListBoxItems();
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -127,6 +127,6 @@
|
||||
<value>261, 17</value>
|
||||
</metadata>
|
||||
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>77</value>
|
||||
<value>25</value>
|
||||
</metadata>
|
||||
</root>
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectAirFighter
|
||||
{
|
||||
internal static class Program
|
||||
@ -10,8 +15,30 @@ namespace ProjectAirFighter
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ServiceCollection serviceCollection = new();
|
||||
ConfigureService(serviceCollection);
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormWarPlaneCollection());
|
||||
using ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormWarPlaneCollection>());
|
||||
}
|
||||
|
||||
private static void ConfigureService(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormWarPlaneCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile(path: "appSetting.json", optional: false, reloadOnChange: true)
|
||||
.Build();
|
||||
|
||||
var logger = new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(configuration)
|
||||
.CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,16 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@ -23,4 +33,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appSetting.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
20
ProjectAirFighter/ProjectAirFighter/appSetting.json
Normal file
20
ProjectAirFighter/ProjectAirFighter/appSetting.json
Normal 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": "ProjectAirFighter"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user