lab7 done

This commit is contained in:
Алексей Тихоненков 2023-12-11 19:14:18 +04:00
parent 3914bd51bb
commit c39c275de2
9 changed files with 132 additions and 40 deletions

View File

@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Exceptions
{
[Serializable]
internal class AntiAirCraftGunNotFoundException : ApplicationException
{
public AntiAirCraftGunNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public AntiAirCraftGunNotFoundException() : base() { }
public AntiAirCraftGunNotFoundException(string message) : base(message) { }
public AntiAirCraftGunNotFoundException(string message, Exception exception) : base(message, exception) { }
protected AntiAirCraftGunNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Exceptions
{
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 context) : base(info, context) { }
}
}

View File

@ -1,6 +1,8 @@
using AntiAircraftGun.DrawingObjects; using AntiAircraftGun.DrawingObjects;
using AntiAircraftGun.Exceptions;
using AntiAircraftGun.Generics; using AntiAircraftGun.Generics;
using AntiAircraftGun.MovementStrategy; using AntiAircraftGun.MovementStrategy;
using Microsoft.VisualBasic.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,12 +12,16 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Serilog;
namespace AntiAircraftGun namespace AntiAircraftGun
{ {
public partial class FormAntiAirCraftGunCollection : Form public partial class FormAntiAirCraftGunCollection : Form
{ {
private readonly AntiAirCraftGunGenericStorage _storage; private readonly AntiAirCraftGunGenericStorage _storage;
public FormAntiAirCraftGunCollection() public FormAntiAirCraftGunCollection()
{ {
InitializeComponent(); InitializeComponent();
@ -59,6 +65,7 @@ namespace AntiAircraftGun
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
Serilog.Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
} }
/// <summary> /// <summary>
/// Выбор набора /// Выбор набора
@ -85,9 +92,10 @@ namespace AntiAircraftGun
if (MessageBox.Show($"Удалить объект{ listBoxStorages.SelectedItem}?", "Удаление", if (MessageBox.Show($"Удалить объект{ listBoxStorages.SelectedItem}?", "Удаление",
MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
?? string.Empty); _storage.DelSet(name);
ReloadObjects(); ReloadObjects();
Serilog.Log.Information($"Удален набор: {name}");
} }
} }
@ -107,16 +115,19 @@ namespace AntiAircraftGun
FormAntiAirCraftGunConfig form = new(); FormAntiAirCraftGunConfig form = new();
form.Show(); form.Show();
Action<BaseDrawingAntiAirCraftGun>? zenitDelegate = new((m) => { Action<BaseDrawingAntiAirCraftGun>? zenitDelegate = new((m) => {
bool q = (obj + m);
if (q) try
{ {
bool q = (obj + m);
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
Serilog.Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowZenits(); pictureBoxCollection.Image = obj.ShowZenits();
} }
else catch(StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); Serilog.Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
} }
}); });
form.AddEvent(zenitDelegate); form.AddEvent(zenitDelegate);
@ -137,15 +148,25 @@ namespace AntiAircraftGun
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null) try
{ {
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
Serilog.Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowZenits(); pictureBoxCollection.Image = obj.ShowZenits();
} }
else catch(AntiAirCraftGunNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); Serilog.Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException ex)
{
Serilog.Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
} }
} }
@ -174,15 +195,16 @@ namespace AntiAircraftGun
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storage.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Serilog.Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
} }
else catch(Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", Serilog.Log.Warning($"Не удалось сохранить {saveFileDialog.FileName}");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@ -195,19 +217,21 @@ namespace AntiAircraftGun
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", _storage.LoadData(openFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Serilog.Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys) foreach (var collection in _storage.Keys)
{ {
listBoxStorages.Items.Add(collection); listBoxStorages.Items.Add(collection);
} }
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", Serilog.Log.Warning("Не удалось загрузить");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -70,8 +70,7 @@ namespace AntiAircraftGun.Generics
public static T? operator -(AntiAirCraftGunGenericCollection<T, U> collect, int pos) public static T? operator -(AntiAirCraftGunGenericCollection<T, U> collect, int pos)
{ {
T? obj = collect._collection.Get(pos); T? obj = collect._collection.Get(pos);
if (obj != null) collect._collection.Remove(pos);
collect._collection.Remove(pos);
return obj; return obj;
} }

View File

@ -75,7 +75,7 @@ namespace AntiAircraftGun.Generics
public void DelSet(string name) public void DelSet(string name)
{ {
// TODO: Прописать логику для удаления набора // TODO: Прописать логику для удаления набора
if (_zenitStorages.ContainsKey(name) == null) if (!_zenitStorages.ContainsKey(name))
{ {
return; return;
} }
@ -127,7 +127,7 @@ namespace AntiAircraftGun.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалидная операция, нет данных для сохранения");
} }
string toWrite = $"CarStorage{Environment.NewLine}{data}"; string toWrite = $"CarStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
@ -149,7 +149,7 @@ namespace AntiAircraftGun.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new IOException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
@ -157,11 +157,11 @@ namespace AntiAircraftGun.Generics
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
return false; throw new IOException("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("CarStorage")) if (!strs[0].StartsWith("CarStorage"))
{ {
return false; throw new IOException("Неверный формат данных");
} }
_zenitStorages.Clear(); _zenitStorages.Clear();
do do
@ -182,7 +182,7 @@ namespace AntiAircraftGun.Generics
{ {
if (!(collection + zenit)) if (!(collection + zenit))
{ {
return false; throw new Exception("Ошибка добавления в коллекцию");
} }
} }
} }
@ -192,7 +192,7 @@ namespace AntiAircraftGun.Generics
} while (str != null); } while (str != null);
} }
return true; return true;
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using AntiAircraftGun.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -38,16 +39,18 @@ namespace AntiAircraftGun.Generics
public bool Insert(T car) public bool Insert(T car)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
return false; throw new StorageOverflowException(_maxCount);
Insert(car, 0); Insert(car, 0);
return true; return true;
} }
public bool Insert(T car, int position) public bool Insert(T car, int position)
{ {
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false; return false;
_places.Insert(position, car); _places.Insert(position, car);
return true; return true;
} }
@ -60,9 +63,9 @@ namespace AntiAircraftGun.Generics
{ {
// Проверка позиции // Проверка позиции
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
return false; throw new AntiAirCraftGunNotFoundException(position);
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }

View File

@ -0,0 +1,15 @@
using Serilog;
namespace AntiAircraftGun
{
public static class Logger
{
public static void ConfigureLogger()
{
Log.Logger = new LoggerConfiguration()
.WriteTo.File("log.txt")
.MinimumLevel.Debug()
.CreateLogger();
}
}
}

View File

@ -1,3 +1,5 @@
using Microsoft.Extensions.Configuration;
using Serilog;
namespace AntiAircraftGun namespace AntiAircraftGun
{ {
internal static class Program internal static class Program
@ -8,9 +10,11 @@ namespace AntiAircraftGun
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. Log.Logger = new LoggerConfiguration()
ApplicationConfiguration.Initialize(); .ReadFrom.Configuration(new ConfigurationBuilder().AddJsonFile("serilog.json").Build())
.CreateLogger();
ApplicationConfiguration.Initialize();
Application.Run(new FormAntiAirCraftGunCollection()); Application.Run(new FormAntiAirCraftGunCollection());
} }
} }