diff --git a/projectDoubleDeckerBus/projectDoubleDeckerBus/BusNotFoundException.cs b/projectDoubleDeckerBus/projectDoubleDeckerBus/BusNotFoundException.cs
new file mode 100644
index 0000000..e893960
--- /dev/null
+++ b/projectDoubleDeckerBus/projectDoubleDeckerBus/BusNotFoundException.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Runtime.Serialization;
+
+
+namespace projectDoubleDeckerBus.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) { }
+ }
+
+}
diff --git a/projectDoubleDeckerBus/projectDoubleDeckerBus/BusesGenericStorage.cs b/projectDoubleDeckerBus/projectDoubleDeckerBus/BusesGenericStorage.cs
index e534346..820f06d 100644
--- a/projectDoubleDeckerBus/projectDoubleDeckerBus/BusesGenericStorage.cs
+++ b/projectDoubleDeckerBus/projectDoubleDeckerBus/BusesGenericStorage.cs
@@ -6,6 +6,8 @@ using System.Threading.Tasks;
using projectDoubleDeckerBus.Drawings;
using projectDouble_Decker_Bus.MovementStrategy;
using projectDoubleDeckerBus.Generics;
+using System.Text;
+using projectDoubleDeckerBus.Exceptions;
namespace projectDoubleDeckerBus.Generics
{
@@ -55,7 +57,7 @@ namespace projectDoubleDeckerBus.Generics
}
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -74,42 +76,41 @@ namespace projectDoubleDeckerBus.Generics
}
if (data.Length == 0)
{
- return false;
+ throw new Exception("Невалидная операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine("BusStorage");
writer.Write(data.ToString());
- return true;
}
-
}
+
///
/// Загрузка информации по автомобилям в хранилище из файла
///
/// Путь и имя файла
/// true - загрузка прошла успешно, false - ошибка при
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new Exception("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
{
string checker = reader.ReadLine();
if (checker == null)
- return false;
+ throw new Exception("Нет данных для загрузки");
if (!checker.StartsWith("BusStorage"))
- return false;
+ throw new Exception("Неверный формат ввода");
_busStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
- return false;
+ throw new Exception("Нет данных для загрузки");
if (strs == null)
break;
firstinit = false;
@@ -121,20 +122,25 @@ namespace projectDoubleDeckerBus.Generics
data?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight);
if (bus != null)
{
- if (!(collection + bus))
+ try { _ = collection + bus; }
+ catch (BusNotFoundException e)
{
- return false;
+ throw e;
+ }
+ catch (StorageOverflowException e)
+ {
+ throw e;
}
}
}
_busStorages.Add(name, collection);
}
- return true;
}
}
}
-
}
-
+
+
+
diff --git a/projectDoubleDeckerBus/projectDoubleDeckerBus/FormBusCollection.cs b/projectDoubleDeckerBus/projectDoubleDeckerBus/FormBusCollection.cs
index 07b801f..40e6400 100644
--- a/projectDoubleDeckerBus/projectDoubleDeckerBus/FormBusCollection.cs
+++ b/projectDoubleDeckerBus/projectDoubleDeckerBus/FormBusCollection.cs
@@ -10,6 +10,8 @@ using System.Windows.Forms;
using projectDoubleDeckerBus.Drawings;
using projectDouble_Decker_Bus.MovementStrategy;
using projectDoubleDeckerBus.Generics;
+using projectDoubleDeckerBus.Exceptions;
+using Microsoft.Extensions.Logging;
namespace projectDoubleDeckerBus
{
@@ -22,13 +24,17 @@ namespace projectDoubleDeckerBus
///
/// Конструктор
///
- public FormBusCollection()
+
+ private readonly ILogger _logger;
+ public FormBusCollection(ILogger logger)
{
InitializeComponent();
_storage = new BusesGenericStorage(DrawBus.Width, DrawBus.Height);
+ _logger = logger;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
ReloadObjects();
}
+
///
/// Заполнение listBoxObjects
///
@@ -40,11 +46,13 @@ namespace projectDoubleDeckerBus
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
- if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
+ if (listBoxStorages.Items.Count > 0 && (index == -1 || index
+ >= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
- else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
+ else if (listBoxStorages.Items.Count > 0 && index > -1 &&
+ index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
@@ -55,16 +63,21 @@ namespace projectDoubleDeckerBus
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
+ _logger.LogWarning("Добавление пустого объекта");
return;
}
- if (obj + bus)
+ try
{
+ _ = obj + bus;
+
MessageBox.Show("Объект добавлен");
DrawBus.Image = obj.ShowBuses();
+ _logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
}
- else
+ catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
+ _logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
}
@@ -96,36 +109,42 @@ namespace projectDoubleDeckerBus
private void ButtonRemoveBus_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
+ {
+ _logger.LogWarning("Удаление объекта из несуществующего набора");
+ return;
+ }
+ var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
+ string.Empty];
+ if (obj == null)
{
return;
}
- var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
- foreach (var it in maskedTextBoxNumber.Text)
- if (it < '0' || it > '9')
+ int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
+ try
+ {
+ if (obj - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ DrawBus.Image = obj.ShowBuses();
+ _logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
+ }
+ else
{
MessageBox.Show("Не удалось удалить объект");
- return;
+ _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
- if (maskedTextBoxNumber.Text.Length == 0)
- {
- MessageBox.Show("Не удалось удалить объект");
- return;
}
- int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
- if (obj - pos != null)
+ catch (BusNotFoundException ex)
{
- MessageBox.Show("Объект удален");
- DrawBus.Image = obj.ShowBuses();
- }
- else
- {
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
+ _logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
+
}
///
/// Обновление рисунка по набору
@@ -157,6 +176,7 @@ namespace projectDoubleDeckerBus
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
+ _logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}");
}
///
@@ -166,7 +186,25 @@ namespace projectDoubleDeckerBus
///
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{
- DrawBus.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBuses();
+ DrawBus.Image =
+ _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBuses();
+ }
+ private void ButtonDelObject_Click(object sender, EventArgs e)
+ {
+ if (listBoxStorages.SelectedIndex == -1)
+ {
+ _logger.LogWarning("Удаление невыбранного набора");
+ return;
+ }
+ string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
+ if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo,
+ MessageBoxIcon.Question) == DialogResult.Yes)
+ {
+ _storage.DelSet(listBoxStorages.SelectedItem.ToString()
+ ?? string.Empty);
+ ReloadObjects();
+ _logger.LogInformation($"Удален набор: {name}");
+ }
}
///
@@ -174,31 +212,23 @@ namespace projectDoubleDeckerBus
///
///
///
- private void ButtonDelObject_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();
- }
+
+
- }
-
- private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
+private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.SaveData(saveFileDialog.FileName))
+ try
{
+ _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
@@ -207,14 +237,17 @@ namespace projectDoubleDeckerBus
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.LoadData(openFileDialog.FileName))
+ try
{
+ _storage.LoadData(openFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
diff --git a/projectDoubleDeckerBus/projectDoubleDeckerBus/Program.cs b/projectDoubleDeckerBus/projectDoubleDeckerBus/Program.cs
index d561a66..83616a8 100644
--- a/projectDoubleDeckerBus/projectDoubleDeckerBus/Program.cs
+++ b/projectDoubleDeckerBus/projectDoubleDeckerBus/Program.cs
@@ -1,17 +1,44 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+using System;
+using System.Windows.Forms;
+using System.IO;
+
namespace projectDoubleDeckerBus
{
- internal static class Program
+ static class Program
{
- ///
- /// The main entry point for the application.
- ///
[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 FormBusCollection());
+ var services = new ServiceCollection();
+ ConfigureServices(services);
+ using (ServiceProvider serviceProvider = services.BuildServiceProvider())
+ {
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+ }
+
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ services.AddSingleton().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);
+ });
+
}
}
}
\ No newline at end of file
diff --git a/projectDoubleDeckerBus/projectDoubleDeckerBus/SetGeneric.cs b/projectDoubleDeckerBus/projectDoubleDeckerBus/SetGeneric.cs
index f635513..346686d 100644
--- a/projectDoubleDeckerBus/projectDoubleDeckerBus/SetGeneric.cs
+++ b/projectDoubleDeckerBus/projectDoubleDeckerBus/SetGeneric.cs
@@ -1,4 +1,5 @@
-using System;
+using projectDoubleDeckerBus.Exceptions;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -42,19 +43,17 @@ namespace projectDoubleDeckerBus.Generics
public bool Insert(T bus, int position)
{
if (position < 0 || position >= _maxCount)
- return false;
+ throw new BusNotFoundException(position);
if (Count >= _maxCount)
- return false;
+ throw new StorageOverflowException(position);
_places.Insert(0, bus);
return true;
}
public bool Remove(int position)
{
- if (position < 0 || position > _maxCount)
- return false;
- if (position >= Count)
- return false;
+ if (position < 0 || position > _maxCount || position >= Count)
+ throw new BusNotFoundException(position);
_places.RemoveAt(position);
return true;
}
diff --git a/projectDoubleDeckerBus/projectDoubleDeckerBus/StorageOverflowException.cs b/projectDoubleDeckerBus/projectDoubleDeckerBus/StorageOverflowException.cs
new file mode 100644
index 0000000..3db63df
--- /dev/null
+++ b/projectDoubleDeckerBus/projectDoubleDeckerBus/StorageOverflowException.cs
@@ -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 projectDoubleDeckerBus.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) { }
+ }
+}
diff --git a/projectDoubleDeckerBus/projectDoubleDeckerBus/appsettings.json b/projectDoubleDeckerBus/projectDoubleDeckerBus/appsettings.json
new file mode 100644
index 0000000..51d28fe
--- /dev/null
+++ b/projectDoubleDeckerBus/projectDoubleDeckerBus/appsettings.json
@@ -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": "projectDoubleDeckerBus"
+ }
+ }
+}
\ No newline at end of file
diff --git a/projectDoubleDeckerBus/projectDoubleDeckerBus/projectDoubleDeckerBus.csproj b/projectDoubleDeckerBus/projectDoubleDeckerBus/projectDoubleDeckerBus.csproj
index 13ee123..b3f4c23 100644
--- a/projectDoubleDeckerBus/projectDoubleDeckerBus/projectDoubleDeckerBus.csproj
+++ b/projectDoubleDeckerBus/projectDoubleDeckerBus/projectDoubleDeckerBus.csproj
@@ -8,6 +8,20 @@
enable
+
+
+
+
+
+
+
+
+
+
+
+
+
+
True