Финальный этап

This commit is contained in:
Максим Егоров 2024-10-05 23:17:03 +04:00
parent 8b8c908d41
commit ded89563f9
6 changed files with 43 additions and 69 deletions

View File

@ -260,6 +260,5 @@ namespace Sailboat
private ToolStripMenuItem LoadToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private EventHandler buttonRemoveBoat_Click;
} }
} }

View File

@ -13,14 +13,13 @@ using Sailboat.Exceptions;
using Sailboat.Generics; using Sailboat.Generics;
using Sailboat.MovementStrategy; using Sailboat.MovementStrategy;
namespace Sailboat namespace Sailboat
{ {
public partial class FormBoatCollection : Form public partial class FormBoatCollection : Form
{ {
private readonly BoatsGenericStorage _storage; private readonly BoatsGenericStorage _storage;
private readonly ILogger _logger; private readonly ILogger _logger;
private FormBoatCollection(ILogger<BoatsGenericStorage> logger) public FormBoatCollection(ILogger<FormBoatCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
@ -71,7 +70,6 @@ namespace Sailboat
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Добавление пустого объекта");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
@ -97,7 +95,7 @@ namespace Sailboat
} }
} }
private void ButtonRemoveBoat_Click(object sender, EventArgs e) private void buttonRemoveBoat_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
@ -135,6 +133,7 @@ namespace Sailboat
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}"); _logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
} }
} }
private void buttonRefreshCollection_Click(object sender, EventArgs e) private void buttonRefreshCollection_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
@ -166,8 +165,7 @@ namespace Sailboat
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)
@ -178,10 +176,9 @@ namespace Sailboat
return; return;
} }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) 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.LogInformation($"Удален набор: {name}");
} }
@ -190,17 +187,20 @@ namespace Sailboat
private void SaveToolStripMenuItem_Click(object sender, EventArgs e) private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
try if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
_storage.SaveData(saveFileDialog.FileName); try
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); {
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}"); _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}"); _logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
} }
} }
@ -211,26 +211,21 @@ namespace Sailboat
try try
{ {
_storage.LoadData(openFileDialog.FileName); _storage.LoadData(openFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}"); _logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}"); _logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
} }
} }
ReloadObjects();
} }
private void pictureBoxCollection_Click(object sender, EventArgs e)
{
}
} }
} }

View File

@ -210,7 +210,6 @@
Name = "FormSailboat"; Name = "FormSailboat";
StartPosition = FormStartPosition.CenterScreen; StartPosition = FormStartPosition.CenterScreen;
Text = "Парусник"; Text = "Парусник";
Load += FormSailboat_Load;
((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).EndInit();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();

View File

@ -129,12 +129,6 @@ namespace Sailboat
{ {
SelectedBoat = _drawingBoat; SelectedBoat = _drawingBoat;
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
}
private static void FormSailboat_Load(object sender, EventArgs e)
{
} }
} }
} }

View File

@ -1,8 +1,6 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog; using Serilog;
namespace Sailboat namespace Sailboat
@ -15,16 +13,13 @@ 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();
var services = new ServiceCollection(); var services = new ServiceCollection();
ConfigureServices(services); ConfigureServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider(); using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{ {
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>()); Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
} }
} }
private static void ConfigureServices(ServiceCollection services) private static void ConfigureServices(ServiceCollection services)
@ -42,9 +37,7 @@ namespace Sailboat
option.SetMinimumLevel(LogLevel.Information); option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger); option.AddSerilog(logger);
option.AddNLog("nlog.config");
}); });
} }
} }
} }

View File

@ -1,10 +1,10 @@
using System; using System;
using Sailboat.Exceptions;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms;
using Sailboat.Exceptions;
namespace Sailboat.Generics namespace Sailboat.Generics
{ {
@ -13,7 +13,7 @@ namespace Sailboat.Generics
/// <summary> /// <summary>
/// Список объектов, которые храним /// Список объектов, которые храним
/// </summary> /// </summary>
private readonly List<T?> _places; private readonly List <T?> _places;
/// <summary> /// <summary>
/// Количество объектов в массиве /// Количество объектов в массиве
/// </summary> /// </summary>
@ -38,12 +38,7 @@ namespace Sailboat.Generics
/// <returns></returns> /// <returns></returns>
public bool Insert(T boat) public bool Insert(T boat)
{ {
if (_places.Count == _maxCount) return Insert(boat, 0);
{
throw new StorageOverflowException(_maxCount);
}
Insert(boat, 0);
return true;
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
@ -53,13 +48,12 @@ namespace Sailboat.Generics
/// <returns></returns> /// <returns></returns>
public bool Insert(T boat, int position) public bool Insert(T boat, int position)
{ {
if (_places.Count == _maxCount) if (position < 0 || position >= _maxCount)
throw new BoatNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count)) _places.Insert(0, boat);
{
return false;
}
_places.Insert(position, boat);
return true; return true;
} }
/// <summary> /// <summary>
@ -69,7 +63,7 @@ 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); throw new BoatNotFoundException(position);
} }
@ -87,7 +81,7 @@ namespace Sailboat.Generics
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; return null;
} }
return _places[position]; return _places[position];
} }
@ -95,7 +89,7 @@ namespace Sailboat.Generics
{ {
if (!(position >= 0 && position < Count && _places.Count < _maxCount)) if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{ {
return; return;
} }
_places.Insert(position, value); _places.Insert(position, value);
return; return;
@ -117,4 +111,4 @@ namespace Sailboat.Generics
} }
} }
} }
} }