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

View File

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

View File

@ -1,4 +1,5 @@
using System;
using AntiAircraftGun.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -38,16 +39,18 @@ namespace AntiAircraftGun.Generics
public bool Insert(T car)
{
if (_places.Count == _maxCount)
return false;
throw new StorageOverflowException(_maxCount);
Insert(car, 0);
return true;
}
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;
_places.Insert(position, car);
_places.Insert(position, car);
return true;
}
@ -60,9 +63,9 @@ namespace AntiAircraftGun.Generics
{
// Проверка позиции
if (position < 0 || position >= Count)
return false;
throw new AntiAirCraftGunNotFoundException(position);
_places.RemoveAt(position);
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
{
internal static class Program
@ -8,9 +10,11 @@ namespace AntiAircraftGun
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder().AddJsonFile("serilog.json").Build())
.CreateLogger();
ApplicationConfiguration.Initialize();
Application.Run(new FormAntiAirCraftGunCollection());
}
}