почти готовая лаба 7

This commit is contained in:
Полина Чубыкина 2023-12-19 19:11:26 +04:00
parent 3ef5d8874e
commit daf8812332
9 changed files with 217 additions and 95 deletions

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 Sailboat.Exceptions
{
[Serializable]
internal class BoatNotFoundException : ApplicationException
{
public BoatNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public BoatNotFoundException() : base() { }
public BoatNotFoundException(string message) : base(message) { }
public BoatNotFoundException(string message, Exception exception) :base(message, exception) { }
protected BoatNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -71,14 +71,11 @@ namespace Sailboat.Generics
/// <param name="collect"></param> /// <param name="collect"></param>
/// <param name="pos"></param> /// <param name="pos"></param>
/// <returns></returns> /// <returns></returns>
public static bool operator -(BoatsGenericCollection<T, U> collect, int pos) public static T? operator -(BoatsGenericCollection<T, U> collect, int pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection[pos];
if (obj != null) collect._collection.Remove(pos);
{ return obj;
collect._collection.Remove(pos);
}
return false;
} }
/// <summary> /// <summary>

View File

@ -6,6 +6,7 @@ using System.Threading.Tasks;
using Sailboat.DrawingObjects; using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy; using Sailboat.MovementStrategy;
using Sailboat.Exceptions;
namespace Sailboat.Generics namespace Sailboat.Generics
{ {
@ -46,8 +47,7 @@ namespace Sailboat.Generics
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public BoatsGenericStorage(int pictureWidth, int pictureHeight) public BoatsGenericStorage(int pictureWidth, int pictureHeight)
{ {
_boatStorages = new Dictionary<string, _boatStorages = new Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -97,12 +97,13 @@ namespace Sailboat.Generics
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages) foreach (KeyValuePair<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
{ {
@ -112,73 +113,77 @@ namespace Sailboat.Generics
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
} }
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new InvalidOperationException("Файл не найден, невалидная операция, нет данных для сохранения");
} }
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write($"PlaneStorage{Environment.NewLine}{data}"); writer.WriteLine("BoatStorage");
writer.Write(data.ToString());
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по автомобилям в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка призагрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка призагрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader reader = new StreamReader(filename))
{ {
string str = fs.ReadLine(); string checker = reader.ReadLine();
if (str == null || str.Length == 0) if (checker == null)
throw new NullReferenceException("Нет данных для загрузки");
if (!checker.StartsWith("BoatStorage"))
{ {
return false; //если нет такой записи, то это не те данные
} throw new FormatException("Неверный формат данных");
if (!str.StartsWith("BoatStorage"))
{
return false;
} }
_boatStorages.Clear(); _boatStorages.Clear();
string strs = ""; string strs;
bool firstinit = true;
while ((strs = fs.ReadLine()) != null) while ((strs = reader.ReadLine()) != null)
{ {
if (strs == null && firstinit)
throw new NullReferenceException("Нет данных для загрузки");
if (strs == null) if (strs == null)
{ break;
return false; firstinit = false;
} string name = strs.Split('|')[0];
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight); BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); foreach (string data in strs.Split('|')[1].Split(';'))
foreach (string elem in set)
{ {
DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); DrawingBoat? vehicle = data?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null) if (vehicle != null)
{ {
if (!(collection + boat)) try
{ {
return false; _ = collection + vehicle;
}
catch (BoatNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
} }
} }
} }
_boatStorages.Add(record[0], collection); _boatStorages.Add(name, collection);
} }
return true;
} }
} }
} }
} }

View File

@ -7,34 +7,34 @@ 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 Microsoft.Extensions.Logging;
using Sailboat.DrawingObjects; using Sailboat.DrawingObjects;
using Sailboat.Generics; using Sailboat.Generics;
using Sailboat.MovementStrategy; using Sailboat.MovementStrategy;
using Sailboat.Exceptions;
namespace Sailboat namespace Sailboat
{ {
public partial class FormBoatCollection : Form public partial class FormBoatCollection : Form
{ {
private readonly BoatsGenericStorage _storage; private readonly BoatsGenericStorage _storage;
public FormBoatCollection() private readonly ILogger _logger;
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
private void ReloadObjects() private void ReloadObjects()
{ {
int index = listBoxStorages.SelectedIndex; int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear(); listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) for (int i = 0; i < _storage.Keys.Count; i++)
{ {
listBoxStorages.Items.Add(_storage.Keys[i]); listBoxStorages.Items.Add(_storage.Keys[i]);
} }
if (listBoxStorages.Items.Count > 0 && (index == -1 || index if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count)) >= listBoxStorages.Items.Count))
{ {
@ -60,8 +60,8 @@ namespace Sailboat
} }
var formBoatConfig = new FormBoatConfig(); var formBoatConfig = new FormBoatConfig();
formBoatConfig.AddEvent(AddBoat);
formBoatConfig.Show(); formBoatConfig.Show();
formBoatConfig.AddEvent(AddBoat);
} }
private void AddBoat(DrawingBoat drawingBoat) private void AddBoat(DrawingBoat drawingBoat)
@ -70,21 +70,26 @@ namespace Sailboat
{ {
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
string.Empty];
if (obj == null) if (obj == null)
{ {
_logger.LogWarning("Добавление пустого объекта");
return; return;
} }
try
if (obj + drawingBoat)
{ {
MessageBox.Show("Объект добавлен"); if (obj + drawingBoat)
pictureBoxCollection.Image = obj.ShowBoats(); {
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"Добавлен объект {obj}");
}
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show(ex.Message);
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
} }
} }
@ -92,30 +97,41 @@ namespace Sailboat
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Удаление объекта из несуществующего набора");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
string.Empty];
if (obj == null) if (obj == null)
{ {
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
_logger.LogWarning("Отмена удаления объекта");
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null) try
{ {
MessageBox.Show("Объект удален"); if (obj - pos != null)
pictureBoxCollection.Image = obj.ShowBoats(); {
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции{pos}");
pictureBoxCollection.Image = obj.ShowBoats();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
} }
else catch (BoatNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
} }
} }
private void buttonRefreshCollection_Click(object sender, EventArgs e) private void buttonRefreshCollection_Click(object sender, EventArgs e)
@ -138,47 +154,52 @@ namespace Sailboat
{ {
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning("Коллекция не добавлена, не все данные заполнены");
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
} }
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBoxCollection.Image = pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBoats();
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBoats();
} }
private void buttonDelObject_Click(object sender, EventArgs e) private void buttonDelObject_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Удаление невыбранного набора");
return; 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() _storage.DelSet(name);
?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
_logger.LogWarning("Отмена удаления набора");
} }
private void SaveToolStripMenuItem_Click(object sender, EventArgs e) private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
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);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
} }
} }
} }
@ -187,18 +208,19 @@ namespace Sailboat
{ {
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); ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
} }
} }
ReloadObjects();
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Sailboat namespace Sailboat
{ {
internal static class Program internal static class Program
@ -8,10 +13,31 @@ namespace Sailboat
[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.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormBoatCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>().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}appSetting.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,15 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<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.7" />
<PackageReference Include="Serilog.AspNetCore" Version="8.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

@ -4,6 +4,8 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Sailboat.Exceptions;
namespace Sailboat.Generics namespace Sailboat.Generics
{ {
internal class SetGeneric<T> where T : class internal class SetGeneric<T> where T : class
@ -51,10 +53,12 @@ namespace Sailboat.Generics
/// <returns></returns> /// <returns></returns>
public bool Insert(T boat, int position) public bool Insert(T boat, int position)
{ {
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) { if (position < 0 || position >= _maxCount)
return false; throw new BoatNotFoundException(position);
}
_places.Insert(position, boat); if (_places.Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
_places.Insert(0, boat);
return true; return true;
} }
/// <summary> /// <summary>
@ -64,10 +68,9 @@ namespace Sailboat.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position > _maxCount || position >= Count)
{ throw new BoatNotFoundException(position);
return false;
}
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.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": "Sailboat"
}
}
}