Готовая 7 лабораторная

This commit is contained in:
Илья 2023-12-05 14:10:33 +04:00
parent 4d599ac689
commit 14ce4e5d49
9 changed files with 170 additions and 47 deletions

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": "Monorail"
}
}
}

View File

@ -1,6 +1,7 @@
using ProjectMonorail.DrawingObjects;
using Microsoft.Extensions.Logging;
using ProjectMonorail.DrawingObjects;
using ProjectMonorail.Generics;
using System.Windows.Forms;
using ProjectMonorail.Exceptions;
namespace ProjectMonorail
{
@ -14,13 +15,19 @@ namespace ProjectMonorail
/// </summary>
private readonly MonorailsGenericStorage _storage;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMonorailCollection()
public FormMonorailCollection(ILogger<FormMonorailCollection> logger)
{
InitializeComponent();
_storage = new MonorailsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
@ -53,11 +60,13 @@ namespace ProjectMonorail
{
if (string.IsNullOrEmpty(textBoxNameSet.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Not all data are filled in", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Failed attempt to add a set: not all data are filled in");
return;
}
_storage.AddSet(textBoxNameSet.Text);
ReloadObjects();
_logger.LogInformation($"Set added: {textBoxNameSet.Text}");
}
/// <summary>
@ -80,12 +89,16 @@ namespace ProjectMonorail
{
if (listBoxSets.SelectedIndex == -1)
{
_logger.LogWarning($"Failed attempt to delete a set: no set is selected");
return;
}
if (MessageBox.Show($"Удалить набор {listBoxSets.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
string name = listBoxSets.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Delete a set {name}?", "Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxSets.SelectedItem.ToString() ?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Deleted set: {name}");
}
}
@ -101,17 +114,27 @@ namespace ProjectMonorail
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Failed attempt to add a object: set is null");
return;
}
try
{
if (obj + monorail != -1)
{
MessageBox.Show("Объект добавлен");
MessageBox.Show("Object added");
pictureBoxCollection.Image = obj.ShowMonorails();
_logger.LogInformation($"Object added {monorail}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("Failed attempt to add a object");
}
}
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Failed attempt to add a object: {ex.Message}");
}
}
@ -124,6 +147,7 @@ namespace ProjectMonorail
{
if (listBoxSets.SelectedIndex == -1)
{
_logger.LogWarning($"Failed attempt to add a object: no set is selected");
return;
}
var formMonorailConfig = new FormMonorailConfig();
@ -140,30 +164,40 @@ namespace ProjectMonorail
{
if (listBoxSets.SelectedIndex == -1)
{
_logger.LogWarning($"Failed attempt to delete a object: no set is selected");
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Failed attempt to delete a object: set is null");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Delete a object?", "Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
if (obj - pos)
{
MessageBox.Show("Объект удален");
MessageBox.Show("Object deleted");
pictureBoxCollection.Image = obj.ShowMonorails();
_logger.LogInformation($"Deleted object in position: {pos}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Failed attempt to delete a object");
}
}
catch (MonorailNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Failed attempt to delete a object: {ex.Message}");
}
}
@ -197,15 +231,18 @@ namespace ProjectMonorail
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Save was successful",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"File saved successfully: {saveFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Save failed", "Result",
MessageBox.Show($"Save failed: {ex.Message}", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"File saving failed: {ex.Message}");
}
}
}
@ -219,16 +256,19 @@ namespace ProjectMonorail
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Load was successful",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
_logger.LogInformation($"File loaded successfully: {openFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Load failed", "Result",
MessageBox.Show($"Load failed: {ex.Message}", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"File loading failed: {ex.Message}");
}
}
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Exceptions
{
[Serializable]
internal class MonorailNotFoundException : ApplicationException
{
public MonorailNotFoundException(int i) : base($"Object not found by position {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

@ -80,12 +80,8 @@ namespace ProjectMonorail.Generics
public static bool operator -(MonorailsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
return collect._collection.Remove(pos);
}
return false;
}
/// <summary>
/// Получение объекта IMoveableObject

View File

@ -95,8 +95,7 @@ namespace ProjectMonorail.Generics
/// Сохранение информации по монорельсам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -114,35 +113,33 @@ namespace ProjectMonorail.Generics
}
if (data.Length == 0)
{
return false;
throw new Exception("Invalid operation, no data to save");
}
using StreamWriter sw = new(filename);
sw.Write($"MonorailStorage{Environment.NewLine}{data}");
return true;
}
/// <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("File not found");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new NullReferenceException("No data to load");
}
if (!str.StartsWith("MonorailStorage"))
{
//если нет такой записи, то это не те данные
return false;
throw new InvalidDataException("Invalid data format");
}
_monorailsStorages.Clear();
while ((str = sr.ReadLine()) != null)
@ -161,14 +158,13 @@ namespace ProjectMonorail.Generics
{
if (collection + monorail == -1)
{
return false;
throw new ApplicationException("Error adding to collection");
}
}
}
_monorailsStorages.Add(record[0], collection);
}
}
return true;
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectMonorail
{
internal static class Program
@ -11,7 +16,29 @@ namespace ProjectMonorail
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMonorailCollection());
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 =>
{
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.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" 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

@ -1,4 +1,7 @@
namespace ProjectMonorail.Generics
using ProjectMonorail.Exceptions;
using System.Collections.Generic;
namespace ProjectMonorail.Generics
{
/// <summary>
/// Параметризованный набор объектов
@ -49,8 +52,10 @@
/// <returns></returns>
public int Insert(T monorail, int position)
{
if (position < 0 || position > Count || Count >= _maxCount)
return -1;
if (position < 0 || position > Count)
throw new MonorailNotFoundException("Impossible to insert");
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
_places.Insert(position, monorail);
return position;
@ -64,7 +69,7 @@
public bool Remove(int position)
{
if (position < 0 || position >= Count)
return false;
throw new MonorailNotFoundException(position);
_places.RemoveAt(position);
return true;
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"The set has exceeded the allowable count: { 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) { }
}
}