Начало

This commit is contained in:
DyCTaTOR 2023-12-04 22:01:10 +04:00
parent dcb5a06f7f
commit a8c6ceef37
7 changed files with 148 additions and 52 deletions

View File

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

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Monorail.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

@ -8,8 +8,12 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Monorail.DrawningObjects; using Monorail.DrawningObjects;
using Monorail.Exceptions;
using Monorail.Generics; using Monorail.Generics;
using Monorail.MovementStrategy; using Monorail.MovementStrategy;
using Monorail.Exceptions;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
namespace Monorail namespace Monorail
{ {
@ -17,12 +21,16 @@ namespace Monorail
public partial class FormMonorailCollection : Form public partial class FormMonorailCollection : Form
{ {
private readonly MonorailsGenericStorage _storage; private readonly MonorailsGenericStorage _storage;
private readonly ILogger _logger;
readonly int countPlace = 21; readonly int countPlace = 21;
public FormMonorailCollection() public FormMonorailCollection(ILogger<FormMonorailCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new MonorailsGenericStorage _storage = new MonorailsGenericStorage
(pictureBoxCollection.Width, pictureBoxCollection.Height); (pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
private void ReloadObjects() private void ReloadObjects()
{ {
@ -49,11 +57,13 @@ namespace Monorail
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не все данные заполнены");
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}");
} }
private void ListBoxObjects_SelectedIndexChanged(object sender, private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e) EventArgs e)
@ -67,12 +77,16 @@ EventArgs e)
{ {
return; return;
} }
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?",
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект{name}?",
"Удаление", MessageBoxButtons.YesNo, "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
private void ButtonAddMonorail_Click(object sender, EventArgs e) private void ButtonAddMonorail_Click(object sender, EventArgs e)
@ -103,18 +117,22 @@ EventArgs e)
{ {
return; return;
} }
try
int addedIndex = obj + monorail;
if (addedIndex != -1 && addedIndex < countPlace)
{ {
MessageBox.Show("Объект добавлен"); int addedIndex = obj + monorail;
pictureBoxCollection.Image = obj.ShowMonorails(); if (addedIndex != -1 && addedIndex < countPlace)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowMonorails();
_logger.LogInformation($"Добавлен монорельс");
}
}
catch(StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning("Не удалось добавить объект");
} }
else
{
MessageBox.Show("Не удалось добавить объект");
}
} }
private void ButtonRemoveMonorail_Click(object sender, EventArgs e) private void ButtonRemoveMonorail_Click(object sender, EventArgs e)
{ {
@ -135,24 +153,20 @@ EventArgs e)
{ {
return; return;
} }
int pos; int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (maskedTextBoxNumber.Text == "") try
{ {
MessageBox.Show("Введите позицию элемента выше"); if (obj - pos != null)
return; {
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowMonorails();
_logger.LogInformation("Объект удален");
}
} }
else catch (MonorailNotFoundException ex)
{ {
pos = Convert.ToInt32(maskedTextBoxNumber.Text); MessageBox.Show(ex.Message);
} _logger.LogWarning($"Не удалось удалить объект. Исключение: {ex}");
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowMonorails();
}
else
{
MessageBox.Show("Не удалось удалить объект");
} }
} }
private void ButtonRefreshCollection_Click(object sender, EventArgs e) private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@ -172,15 +186,16 @@ EventArgs e)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}",
MessageBoxButtons.OK, MessageBoxIcon.Error); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@ -188,17 +203,17 @@ EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", MessageBox.Show("Загрузка прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} ReloadObjects();
else } catch(MonorailNotFoundException ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBox.Show($"Не загрузилось {ex.Message}",
MessageBoxButtons.OK, MessageBoxIcon.Error); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
ReloadObjects();
} }
} }
} }

View File

@ -52,7 +52,7 @@ namespace Monorail.Generics
return _monorailsStorages[ind]; return _monorailsStorages[ind];
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -72,28 +72,28 @@ namespace Monorail.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалиданя операция, нет данных для сохранения");
} }
using StreamWriter sw = new(filename); using StreamWriter sw = new(filename);
sw.Write($"MonorailStorage{Environment.NewLine}{data}"); sw.Write($"MonorailStorage{Environment.NewLine}{data}");
return true; return;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не найден");
} }
using (StreamReader sr = File.OpenText(filename)) using (StreamReader sr = File.OpenText(filename))
{ {
string str = sr.ReadLine(); string str = sr.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (!str.StartsWith("MonorailStorage")) if (!str.StartsWith("MonorailStorage"))
{ {
return false; throw new Exception("Неверный формат данных");
} }
_monorailsStorages.Clear(); _monorailsStorages.Clear();
@ -101,11 +101,6 @@ namespace Monorail.Generics
while ((strs = sr.ReadLine()) != null) while ((strs = sr.ReadLine()) != null)
{ {
if (strs == null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2) if (record.Length != 2)
{ {
@ -122,15 +117,14 @@ namespace Monorail.Generics
{ {
if ((collection + monorail) == -1) if ((collection + monorail) == -1)
{ {
return false; throw new Exception("Ошибка добавления в коллекцию");
} }
} }
} }
_monorailsStorages.Add(record[0], collection); _monorailsStorages.Add(record[0], collection);
} }
return true;
} }
} }
} }
} }

View File

@ -8,4 +8,14 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Xml" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project> </Project>

View File

@ -1,3 +1,12 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
using System.Configuration;
using Serilog.Settings.AppSettings;
using Serilog.Settings.Xml;
using Serilog.Sinks.File;
namespace Monorail namespace Monorail
{ {
internal static class Program internal static class Program
@ -11,7 +20,30 @@ namespace Monorail
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormMonorailCollection());
string logFolderPath = Path.Combine(AppContext.BaseDirectory, "Logs");
string logFilePath = Path.Combine(logFolderPath, "monoraillog-{Date}.log");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day)
.CreateLogger();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMonorailCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMonorailCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(Log.Logger);
});
} }
} }
} }

View File

@ -0,0 +1,2 @@
MonorailStorage
two|100:100:White;;