This commit is contained in:
Yunusov_Niyaz 2023-12-06 19:46:43 +04:00
parent a96cb7156e
commit 336b0a05fd
8 changed files with 114 additions and 40 deletions

View File

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

View File

@ -55,7 +55,8 @@ namespace ProjectTrolleybus.Generics
{
if (obj == null || collect == null)
return false;
return collect?._collection.Insert(obj) ?? false;
collect?._collection.Insert(obj);
return true;
}
/// <summary>
/// Перегрузка оператора вычитания
@ -66,8 +67,7 @@ namespace ProjectTrolleybus.Generics
public static T? operator -(BusesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
collect._collection.Remove(pos);
collect._collection.Remove(pos);
return obj;
}
/// <summary>

View File

@ -88,7 +88,7 @@ namespace ProjectTrolleybus.Generics
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -107,24 +107,26 @@ namespace ProjectTrolleybus.Generics
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using (StreamWriter streamWriter = new(filename))
{
streamWriter.WriteLine($"BusStorages{Environment.NewLine}{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 IOException("Файл не найден");
}
using (StreamReader streamReader = new(filename))
{
@ -132,11 +134,11 @@ namespace ProjectTrolleybus.Generics
var strings = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strings == null || strings.Length == 0)
{
return false;
throw new IOException("Нет данных для загрузки");
}
if (!strings[0].StartsWith("BusStorages"))
{
return false;
throw new IOException("Неверный формат данных");
}
_busStorages.Clear();
do
@ -156,7 +158,7 @@ namespace ProjectTrolleybus.Generics
{
if (!(collection + bus))
{
return false;
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
@ -164,7 +166,7 @@ namespace ProjectTrolleybus.Generics
str = streamReader.ReadLine();
} while (str != null);
}
return true;
return;
}
}
}

View File

@ -11,6 +11,10 @@ using ProjectTrolleybus.DrawingObjects;
using ProjectTrolleybus.MovementStrategy;
using ProjectTrolleybus.Generics;
using ProjectTrolleybus;
using ProjectTrolleybus.Exceptions;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
using Serilog;
namespace ProjectTrolleybus
{
@ -51,6 +55,7 @@ namespace ProjectTrolleybus
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
@ -64,8 +69,10 @@ namespace ProjectTrolleybus
}
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();
Log.Information($"Удален набор: {name}");
}
}
private void ButtonAddBus_Click(object sender, EventArgs e)
@ -83,14 +90,17 @@ namespace ProjectTrolleybus
form.Show();
Action<DrawingBus>? busDelegate = new((bus) =>
{
if (obj + bus)
try
{
var result = obj + bus;
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBuses();
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
});
form.AddEvent(busDelegate);
@ -111,15 +121,23 @@ namespace ProjectTrolleybus
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var result = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowBuses();
}
else
catch (BusNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message); ;
}
catch (FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@ -139,15 +157,17 @@ namespace ProjectTrolleybus
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -155,19 +175,22 @@ namespace ProjectTrolleybus
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectTrolleybus
{
internal static class Program
@ -8,10 +13,15 @@ namespace ProjectTrolleybus
[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()
.WriteTo.File("log.txt")
.MinimumLevel.Debug()
.CreateLogger();
Application.Run(new FormBusCollection());
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
}
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectTrolleybus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -21,26 +22,28 @@ namespace ProjectTrolleybus.Generics
_places = new List<T?>(count);
}
public bool Insert(T trolleybus)
public void Insert(T trolleybus)
{
if (_places.Count == _maxCount)
return false;
throw new StorageOverflowException(_maxCount);
Insert(trolleybus, 0);
return true;
return;
}
public bool Insert(T trolleybus, int position)
public void Insert(T trolleybus, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
return false;
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
throw new Exception("Неверная позиция для вставки");
_places.Insert(position, trolleybus);
return true;
return;
}
public bool Remove(int position)
{
if (!(position >= 0 && position < Count))
return false;
throw new BusNotFoundException(position);
_places.RemoveAt(position);
return true;
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectTrolleybus.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

@ -16,6 +16,13 @@
</Compile>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>