Лаба 7. Почти готова

This commit is contained in:
Андрей Байгулов 2023-12-10 23:37:25 +04:00
parent c8545fdb07
commit ff8612fc91
8 changed files with 187 additions and 121 deletions

View File

@ -81,7 +81,6 @@
buttonDeleteSet.TabIndex = 2; buttonDeleteSet.TabIndex = 2;
buttonDeleteSet.Text = "Удалить набор"; buttonDeleteSet.Text = "Удалить набор";
buttonDeleteSet.UseVisualStyleBackColor = true; buttonDeleteSet.UseVisualStyleBackColor = true;
buttonDeleteSet.Click += buttonDeleteSet_Click;
// //
// listBoxStorages // listBoxStorages
// //
@ -101,7 +100,6 @@
buttonAddSet.TabIndex = 0; buttonAddSet.TabIndex = 0;
buttonAddSet.Text = "Добавить набор"; buttonAddSet.Text = "Добавить набор";
buttonAddSet.UseVisualStyleBackColor = true; buttonAddSet.UseVisualStyleBackColor = true;
buttonAddSet.Click += buttonAddSet_Click;
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //

View File

@ -8,19 +8,24 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using ElectricLocomotive; using ElectricLocomotive;
using Microsoft.Extensions.Logging;
using ProjectElectricLocomotive.DrawingObjects; using ProjectElectricLocomotive.DrawingObjects;
using ProjectElectricLocomotive.Exceptions;
using ProjectElectricLocomotive.Generics; using ProjectElectricLocomotive.Generics;
using ProjectElectricLocomotive.MovementStrategy; using ProjectElectricLocomotive.MovementStrategy;
namespace ProjectElectricLocomotive namespace ProjectElectricLocomotive
{ {
public partial class FormLocomotiveCollection : Form public partial class FormLocomotiveCollection : Form
{ {
private readonly LocomotivesGenericStorage _storage; private readonly LocomotivesGenericStorage _storage;
public FormLocomotiveCollection() private readonly ILogger _logger;
public FormLocomotiveCollection(ILogger<FormLocomotiveCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new LocomotivesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new LocomotivesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
private void ReloadObjects() private void ReloadObjects()
{ {
@ -40,6 +45,19 @@ namespace ProjectElectricLocomotive
listBoxStorages.SelectedIndex = index; listBoxStorages.SelectedIndex = index;
} }
} }
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxSetName.Text))
{
MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Неудачная попытка. Коллекция не добавлена, не все данные заполнены");
return;
}
_storage.AddSet(textBoxSetName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxSetName.Text}");
}
private void buttonAddLocomotive_Click(object sender, EventArgs e) private void buttonAddLocomotive_Click(object sender, EventArgs e)
{ {
var formLocomotiveConfig = new FormLocomotiveConfig(); var formLocomotiveConfig = new FormLocomotiveConfig();
@ -58,18 +76,40 @@ namespace ProjectElectricLocomotive
{ {
return; return;
} }
try
//проверяем, удалось ли нам загрузить объект
if (obj + loco > -1)
{ {
MessageBox.Show("Объект добавлен"); if (obj + loco > -1)
pictureBoxCollection.Image = obj.ShowLocomotives(); {
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowLocomotives();
_logger.LogInformation($"Добавлен объект {obj}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message);
} }
} }
private void ButtonRemoveObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Набор '{name}' удален");
}
_logger.LogWarning("Отмена удаления набора");
}
private void buttonRemoveLocomotive_Click(object sender, EventArgs e) private void buttonRemoveLocomotive_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) return; if (listBoxStorages.SelectedIndex == -1) return;
@ -81,18 +121,28 @@ namespace ProjectElectricLocomotive
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить объект?", "Удаление", 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("Объект удален"); var removeObj = obj - pos;
pictureBoxCollection.Image = obj.ShowLocomotives(); if (removeObj != null)
pictureBoxCollection.Image = obj.ShowLocomotives(); {
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции{pos}");
pictureBoxCollection.Image = obj.ShowLocomotives();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
} }
else catch (LocomotiveNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"Не найден объект по позиции: {obj}");
} }
} }
private void buttonRefreshCollection_Click(object sender, EventArgs e) private void buttonRefreshCollection_Click(object sender, EventArgs e)
@ -109,68 +159,36 @@ namespace ProjectElectricLocomotive
{ {
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowLocomotives(); pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowLocomotives();
} }
private void buttonAddSet_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxSetName.Text))
{
MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxSetName.Text);
ReloadObjects();
}
private void buttonDeleteSet_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
}
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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); _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}");
} }
} }
} }
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e) private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка завершена!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); _storage.LoadData(openFileDialog.FileName);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
ReloadObjects(); ReloadObjects();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Ошибка загрузки!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
} }
} }
} }

View File

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

View File

@ -10,48 +10,22 @@ namespace ProjectElectricLocomotive.Generics
{ {
internal class LocomotivesGenericStorage internal class LocomotivesGenericStorage
{ {
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>> _locomotivesStorage; readonly Dictionary<string, LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>> _locomotivesStorage;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _locomotivesStorage.Keys.ToList(); public List<string> Keys => _locomotivesStorage.Keys.ToList();
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|'; private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';'; private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':'; private static readonly char _separatorForObject = ':';
private readonly int _pictureWidth; private readonly int _pictureWidth;
private readonly int _pictureHeight; private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public LocomotivesGenericStorage(int pictureWidth, int pictureHeight) public LocomotivesGenericStorage(int pictureWidth, int pictureHeight)
{ {
_locomotivesStorage = new Dictionary<string, LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>>(); _locomotivesStorage = new Dictionary<string, LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name) public void AddSet(string name)
{ {
if (!_locomotivesStorage.ContainsKey(name)) if (!_locomotivesStorage.ContainsKey(name))
@ -59,11 +33,6 @@ namespace ProjectElectricLocomotive.Generics
_locomotivesStorage.Add(name, new LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>(_pictureWidth, _pictureHeight)); _locomotivesStorage.Add(name, new LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>(_pictureWidth, _pictureHeight));
} }
} }
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (_locomotivesStorage.ContainsKey(name)) if (_locomotivesStorage.ContainsKey(name))
@ -71,13 +40,6 @@ namespace ProjectElectricLocomotive.Generics
_locomotivesStorage.Remove(name); _locomotivesStorage.Remove(name);
} }
} }
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>? public LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>?
this[string ind] this[string ind]
{ {
@ -90,12 +52,7 @@ namespace ProjectElectricLocomotive.Generics
return null; return null;
} }
} }
/// <summary> public void SaveData(string filename)
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -113,25 +70,20 @@ namespace ProjectElectricLocomotive.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Нет данных для записи, ошибка");
} }
using StreamWriter fs = new StreamWriter(filename); using StreamWriter fs = new StreamWriter(filename);
{ {
fs.WriteLine($"LocomotiveStorage{Environment.NewLine}"); fs.WriteLine($"LocomotiveStorage{Environment.NewLine}");
fs.WriteLine(data); fs.WriteLine(data);
} }
return true; return;
} }
/// <summary> public void LoadData(string filename)
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
@ -141,13 +93,13 @@ namespace ProjectElectricLocomotive.Generics
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new IOException("Нет данных для загрузки");
} }
if (!str.StartsWith("LocomotiveStorage")) if (!str.StartsWith("LocomotiveStorage"))
{ {
//если нет такой записи, то это не те данные //если нет такой записи, то это не те данные
return false; throw new FileFormatException("Неверный формат данных");
} }
_locomotivesStorage.Clear(); _locomotivesStorage.Clear();
@ -159,7 +111,7 @@ namespace ProjectElectricLocomotive.Generics
if (strs == null) if (strs == null)
{ {
return false; throw new FileNotFoundException("Нет данных для загрузки");
} }
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
@ -174,15 +126,15 @@ namespace ProjectElectricLocomotive.Generics
DrawingLocomotive? loco = elem?.CreateDrawningLocomotive(_separatorForObject, _pictureWidth, _pictureHeight); DrawingLocomotive? loco = elem?.CreateDrawningLocomotive(_separatorForObject, _pictureWidth, _pictureHeight);
if (loco != null) if (loco != null)
{ {
if ((collection + loco) == -1) if ((collection + loco) == -1) // for my realization it's -1, for eegov's realization it's boolean
{ {
return false; throw new Exception("Ошибка добавления ");
} }
} }
} }
_locomotivesStorage.Add(record[0], collection); _locomotivesStorage.Add(record[0], collection);
} }
return true; return;
} }
} }
} }

View File

@ -1,5 +1,9 @@
using ProjectElectricLocomotive; using ProjectElectricLocomotive;
using System.Drawing; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ElectricLocomotive namespace ElectricLocomotive
{ {
@ -8,8 +12,32 @@ namespace ElectricLocomotive
[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 FormLocomotiveCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormLocomotiveCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormLocomotiveCollection>().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

@ -8,6 +8,17 @@
<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="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectElectricLocomotive
{
[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": "log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Locomotives"
}
}
}