ISEbd-22. Baygulov A.A. Lab work 07 #8

Closed
tellsense wants to merge 6 commits from lab7 into lab6
10 changed files with 213 additions and 134 deletions

View File

@ -33,11 +33,11 @@
textBoxSetName = new TextBox();
buttonDeleteSet = new Button();
listBoxStorages = new ListBox();
ButtonAddLocomotive = new Button();
buttonAddSet = new Button();
maskedTextBoxNumber = new MaskedTextBox();
ButtonRefreshCollection = new Button();
ButtonRemoveLocomotive = new Button();
ButtonAddLocomotive = new Button();
pictureBoxCollection = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
@ -81,7 +81,7 @@
buttonDeleteSet.TabIndex = 2;
buttonDeleteSet.Text = "Удалить набор";
buttonDeleteSet.UseVisualStyleBackColor = true;
buttonDeleteSet.Click += buttonDeleteSet_Click;
buttonDeleteSet.Click += ButtonRemoveObject_Click;
//
// listBoxStorages
//
@ -93,6 +93,16 @@
listBoxStorages.TabIndex = 1;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
//
// ButtonAddLocomotive
//
ButtonAddLocomotive.Location = new Point(6, 269);
ButtonAddLocomotive.Name = "ButtonAddLocomotive";
ButtonAddLocomotive.Size = new Size(226, 39);
ButtonAddLocomotive.TabIndex = 0;
ButtonAddLocomotive.Text = "Добавить локомотив";
ButtonAddLocomotive.UseVisualStyleBackColor = true;
ButtonAddLocomotive.Click += buttonAddLocomotive_Click;
//
// buttonAddSet
//
buttonAddSet.Location = new Point(6, 67);
@ -101,7 +111,7 @@
buttonAddSet.TabIndex = 0;
buttonAddSet.Text = "Добавить набор";
buttonAddSet.UseVisualStyleBackColor = true;
buttonAddSet.Click += buttonAddSet_Click;
buttonAddSet.Click += ButtonAddObject_Click;
//
// maskedTextBoxNumber
//
@ -130,16 +140,6 @@
ButtonRemoveLocomotive.UseVisualStyleBackColor = true;
ButtonRemoveLocomotive.Click += buttonRemoveLocomotive_Click;
//
// ButtonAddLocomotive
//
ButtonAddLocomotive.Location = new Point(6, 269);
ButtonAddLocomotive.Name = "ButtonAddLocomotive";
ButtonAddLocomotive.Size = new Size(226, 39);
ButtonAddLocomotive.TabIndex = 0;
ButtonAddLocomotive.Text = "Добавить локомотив";
ButtonAddLocomotive.UseVisualStyleBackColor = true;
ButtonAddLocomotive.Click += buttonAddLocomotive_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(6, 24);

View File

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

@ -15,7 +15,7 @@ namespace ProjectElectricLocomotive.Generics
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 200;
private readonly int _placeSizeHeight = 120;
private readonly int _placeSizeHeight = 130;
private readonly SetGeneric<T> _collection;
public LocomotivesGenericCollection(int picWidth, int picHeight)
{

View File

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

View File

@ -1,5 +1,9 @@
using ProjectElectricLocomotive;
using System.Drawing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ElectricLocomotive
{
@ -8,8 +12,32 @@ namespace ElectricLocomotive
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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>
</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>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectElectricLocomotive.Exceptions;
namespace ProjectElectricLocomotive.Generics
{
@ -29,7 +30,13 @@ namespace ProjectElectricLocomotive.Generics
public int Insert(T loco, int position)
{
if (position < 0 || position >= _maxCount) return -1;
if (_places.Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
if (position < 0 || position >= _maxCount)
{
return -1;
}
_places.Insert(position, loco);
return position;
}
@ -40,6 +47,8 @@ namespace ProjectElectricLocomotive.Generics
return null;
T? tmp = _places[position];
if (tmp == null)
throw new LocomotiveNotFoundException(position);
_places[position] = null;
return tmp;
}

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": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Locomotives"
}
}
}