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

This commit is contained in:
DavidMakarov 2023-12-01 16:25:51 +04:00
parent 108233b501
commit b53b5951f1
9 changed files with 192 additions and 48 deletions

View File

@ -0,0 +1,15 @@
using System.Runtime.Serialization;
namespace AirplaneWithRadar.Exceptions
{
[Serializable]
internal class AirplaneNotFoundException : ApplicationException
{
public AirplaneNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public AirplaneNotFoundException() : base() { }
public AirplaneNotFoundException(string message) : base(message) { }
public AirplaneNotFoundException(string message, Exception exception) : base(message, exception)
{ }
protected AirplaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -13,4 +13,14 @@
<Compile Remove="GenericClass.cs" />
</ItemGroup>
<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.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions" Version="2.2.2" />
</ItemGroup>
</Project>

View File

@ -1,6 +1,5 @@
using AirplaneWithRadar.PaintObjects;
using AirplaneWithRadar.MovementStrategy;
using System.Text;
namespace AirplaneWithRadar.Generics
{
@ -34,10 +33,6 @@ namespace AirplaneWithRadar.Generics
public static bool operator -(AirplanesGenericCollection<T, U> collect, int pos)
{
T? obj = collect.collection[pos];
if (obj == null)
{
return false;
}
return collect.collection.Remove(pos);
}

View File

@ -1,11 +1,13 @@
using AirplaneWithRadar.PaintObjects;
using AirplaneWithRadar.MovementStrategy;
using System.Text;
using AirplaneWithRadar.Exceptions;
namespace AirplaneWithRadar.Generics
{
internal class AirplanesGenericStorage
{
readonly Dictionary<string, AirplanesGenericCollection<PaintAirplane, PaintObjectAirplane>> airplaneStorages;
public List<string> Keys => airplaneStorages.Keys.ToList();
private readonly int pictWidth;
@ -20,7 +22,7 @@ namespace AirplaneWithRadar.Generics
pictWidth = pictureWidth;
pictHeight = pictureHeight;
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -38,31 +40,31 @@ namespace AirplaneWithRadar.Generics
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалиданая операция, нет данных для сохранения");
}
string strs = data.ToString();
using (StreamWriter sr = new StreamWriter(filename)) {
sr.WriteLine("AirplaneStorage");
sr.WriteLine(strs);
}
return true;
return;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
{
string checker = reader.ReadLine();
if (checker == null)
{
return false;
throw new Exception("Нет данных для загрузки");
}
if (!checker.StartsWith("AirplaneStorage"))
{
return false;
throw new Exception("Неверный формат данных");
}
airplaneStorages.Clear();
string strs;
@ -70,7 +72,7 @@ namespace AirplaneWithRadar.Generics
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
return false;
return;
if (strs == null)
break;
if (strs == String.Empty)
@ -84,17 +86,22 @@ namespace AirplaneWithRadar.Generics
data?.CreatePaintAirplane(separatorForObject, pictWidth, pictHeight);
if (airplane != null)
{
if (collection + airplane == -1)
try {
_ = collection + airplane;
}
catch (AirplaneNotFoundException e)
{
return false;
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
airplaneStorages.Add(name, collection);
}
return true;
return;
}
}

View File

@ -1,14 +1,20 @@
using AirplaneWithRadar.Generics;
using AirplaneWithRadar.Exceptions;
using Microsoft.Extensions.Logging;
namespace AirplaneWithRadar
{
public partial class FormAirplaneCollection : Form
{
private readonly AirplanesGenericStorage storage;
public FormAirplaneCollection()
private readonly ILogger logger;
public FormAirplaneCollection(ILogger<FormAirplaneCollection> logger)
{
InitializeComponent();
storage = new AirplanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
this.logger = logger;
}
private void ReloadObjects()
@ -33,11 +39,12 @@ namespace AirplaneWithRadar
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.LogWarning("Пустое название набора");
return;
}
storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{
@ -48,12 +55,17 @@ namespace AirplaneWithRadar
{
if (listBoxStorages.SelectedIndex == -1)
{
logger.LogWarning("Удаление невыбранного набора");
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
logger.LogInformation($"Удален набор: {name}");
}
}
private void ButtonAddAirplane_Click(object sender, EventArgs e)
@ -71,22 +83,32 @@ namespace AirplaneWithRadar
formAirplaneConfig.AddEvent(airplane =>
{
if (listBoxStorages.SelectedIndex != -1)
try
{
var obj = storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty];
if (obj != null)
if (listBoxStorages.SelectedIndex != -1)
{
if (obj + airplane != 1)
var obj = storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty];
if (obj != null)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowAirplanes();
}
else
{
MessageBox.Show("Не удалось добавить объект");
if (obj + airplane != 1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowAirplanes();
logger.LogInformation($"Добавлен объект: {airplane}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show($"Ошибка при добавлении: {ex.Message}");
logger.LogWarning($"Ошибка: {ex.Message}");
}
});
formAirplaneConfig.Show();
}
@ -95,6 +117,7 @@ namespace AirplaneWithRadar
{
if (listBoxStorages.SelectedIndex == -1)
{
logger.LogWarning("Удаление из невыбранного набора");
return;
}
var obj = storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
@ -107,15 +130,26 @@ namespace AirplaneWithRadar
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != false)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowAirplanes();
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowAirplanes();
logger.LogInformation($"Удалён объект на позиции: {pos}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
else
catch (AirplaneNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
logger.LogWarning($"Ошибка: {ex.Message}");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@ -135,33 +169,41 @@ namespace AirplaneWithRadar
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (storage.SaveData(saveFileDialog.FileName))
try
{
storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
logger.LogInformation($"Файл сохранён успешно: {saveFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.LogWarning($"Ошибка при сохранении: {ex.Message}");
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (storage.LoadData(openFileDialog.FileName))
try
{
storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка произошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
logger.LogInformation($"Файл загружен успешно: {openFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не загузилось", "Результат",
MessageBox.Show($"Не загузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.LogWarning($"Ошибка при загрузке: {ex.Message}");
}
ReloadObjects();
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AirplaneWithRadar
{
internal static class Program
@ -11,7 +17,32 @@ namespace AirplaneWithRadar
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAirplaneCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormAirplaneCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormAirplaneCollection>().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}appsettings.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -1,4 +1,6 @@
namespace AirplaneWithRadar.Generics;
using AirplaneWithRadar.Exceptions;
namespace AirplaneWithRadar.Generics;
internal class SetGeneric<T>
where T : class
@ -27,7 +29,12 @@ internal class SetGeneric<T>
emptyPosition = i;
break;
}
if (i+1 >= maxCount)
{
throw new StorageOverflowException(maxCount);
}
}
if (emptyPosition < 0)
{
places.Add(airplane);
@ -38,6 +45,10 @@ internal class SetGeneric<T>
}
public int Insert(T airplane, int position)
{
if (position > maxCount)
{
throw new StorageOverflowException(maxCount);
}
if (position > Count || position < 0)
{
return -1;
@ -61,7 +72,6 @@ internal class SetGeneric<T>
{
return -1;
}
for (int i = emptyPosition; i > position; i--)
{
places[i] = places[i - 1];
@ -74,7 +84,7 @@ internal class SetGeneric<T>
{
if ((position >= Count && position < 0) || places[position] == null)
{
return false;
throw new AirplaneNotFoundException(position);
}
places[position]=null;
return true;

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace AirplaneWithRadar.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

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": "AirplaneWithRadar"
}
}
}