Боровков М В ПИбд-22 7 лабораторная работа #8
@ -8,7 +8,7 @@ using System.Threading.Tasks;
|
||||
namespace ProjectElectricLocomotive.DrawningObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Расширение для класса EntityCar
|
||||
/// Расширение для класса EntityLocomotive
|
||||
/// </summary>
|
||||
public static class ExtentionDrawningLocomotive
|
||||
{
|
||||
|
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
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 innerException) : base(message, innerException) { }
|
||||
protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
19
ElectricLocomotive/Exceptions/StorageOverflowException.cs
Normal file
19
ElectricLocomotive/Exceptions/StorageOverflowException.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectElectricLocomotive.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) { }
|
||||
}
|
||||
}
|
@ -149,6 +149,6 @@ namespace ProjectElectricLocomotive.Generics
|
||||
/// <summary>
|
||||
/// Получение объектов коллекции
|
||||
/// </summary>
|
||||
public IEnumerable<T?> GetCars => _collection.GetLocomotives();
|
||||
public IEnumerable<T?> GetLocomotives => _collection.GetLocomotives();
|
||||
}
|
||||
}
|
@ -123,7 +123,7 @@ namespace ProjectElectricLocomotive.Generics
|
||||
sw.WriteLine("LocomotiveStorage");
|
||||
if (_locomotiveStorage.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("Невалиданя операция, нет данных длясохранения");
|
||||
}
|
||||
foreach (
|
||||
KeyValuePair<string, LocomotivesGenericCollection<
|
||||
@ -132,7 +132,7 @@ namespace ProjectElectricLocomotive.Generics
|
||||
{
|
||||
sw.Write(record.Key);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
foreach (DrawningLocomotive? elem in record.Value.GetCars)
|
||||
foreach (DrawningLocomotive? elem in record.Value.GetLocomotives)
|
||||
{
|
||||
sw.Write(
|
||||
$"{elem?.GetDataForSave(_separatorForObject)}" +
|
||||
@ -152,16 +152,16 @@ namespace ProjectElectricLocomotive.Generics
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException($"Файл {filename} не найден");
|
||||
}
|
||||
string bufferTextFromFile = "";
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
string line;
|
||||
if (!((line = sr.ReadLine() != null) && line.StartsWith("LocomotiveStorage")))
|
||||
if (!(((line = sr.ReadLine()) != null) && line.StartsWith("LocomotiveStorage")))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
throw new ArgumentException("Неверный формат данных");
|
||||
}
|
||||
_locomotiveStorage.Clear();
|
||||
while ((line = sr.ReadLine()) != null)
|
||||
@ -185,7 +185,7 @@ namespace ProjectElectricLocomotive.Generics
|
||||
{
|
||||
if ((collection + locomotive) == 0)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("Ошибкадобавления в коллекцию");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectElectricLocomotive.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -43,7 +44,7 @@ namespace ProjectElectricLocomotive.Generics
|
||||
public bool Insert(T locomotive)
|
||||
{
|
||||
if (_places.Count >= _maxCount) {
|
||||
return false;
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
}
|
||||
_places.Insert(0, locomotive);
|
||||
return true;
|
||||
@ -70,11 +71,10 @@ namespace ProjectElectricLocomotive.Generics
|
||||
/// <returns></returns>
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if (position >= Count || position < 0)
|
||||
if (position >= Count || position < 0 || _places[position] == null)
|
||||
{
|
||||
return false;
|
||||
throw new LocomotiveNotFoundException(position);
|
||||
}
|
||||
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
|
||||
@ -90,7 +90,7 @@ namespace ProjectElectricLocomotive.Generics
|
||||
{
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
return null;
|
||||
throw new LocomotiveNotFoundException(position);
|
||||
}
|
||||
return _places[position];
|
||||
}
|
||||
|
@ -1,12 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectElectricLocomotive.DrawningObjects;
|
||||
using ProjectElectricLocomotive.Exceptions;
|
||||
using ProjectElectricLocomotive.Generics;
|
||||
using ProjectElectricLocomotive.MovementStrategy;
|
||||
using System.Windows.Forms;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace ProjectElectricLocomotive
|
||||
{
|
||||
@ -21,15 +18,20 @@ namespace ProjectElectricLocomotive
|
||||
/// </summary>
|
||||
private readonly LocomotivesGenericStorage _storage;
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormLocomotiveCollection()
|
||||
public FormLocomotiveCollection(ILogger<FormLocomotiveCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new LocomotivesGenericStorage(
|
||||
pictureBoxCollection.Width,
|
||||
pictureBoxCollection.Height
|
||||
);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -67,6 +69,7 @@ namespace ProjectElectricLocomotive
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -90,12 +93,14 @@ namespace ProjectElectricLocomotive
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?",
|
||||
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
|
||||
if (MessageBox.Show($"Удалить объект {name}?",
|
||||
"Удаление", MessageBoxButtons.YesNo,
|
||||
MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
|
||||
_storage.DelSet(name);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удален набор: {name}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -122,15 +127,25 @@ namespace ProjectElectricLocomotive
|
||||
return;
|
||||
}
|
||||
SelectedLocomotive.SetPictureSize(pictureBoxCollection.Size);
|
||||
if (obj + SelectedLocomotive > 0)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
if (obj + SelectedLocomotive > 0)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
|
||||
pictureBoxCollection.Image = obj.ShowLocomotives();
|
||||
pictureBoxCollection.Image = obj.ShowLocomotives();
|
||||
_logger.LogInformation($"Объект {obj.GetType()} добавлен");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogInformation($"Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (StorageOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning(ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
@ -165,14 +180,24 @@ namespace ProjectElectricLocomotive
|
||||
{
|
||||
pos = 0;
|
||||
}
|
||||
if (obj - pos != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowLocomotives();
|
||||
if (obj - pos != -1)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowLocomotives();
|
||||
_logger.LogInformation($"Объект {pos} удален");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogInformation($"Не удалось удалить объект {pos}");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (LocomotiveNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning(ex.ToString());
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -205,15 +230,19 @@ namespace ProjectElectricLocomotive
|
||||
saveFileDialog.Title = "Сохранение";
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation($"Сохранение в {saveFileDialog.FileName} прошло успешно");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation($"Не удалось сохранить в {saveFileDialog.FileName}: {ex.Message}");
|
||||
_logger.LogWarning(ex.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -225,16 +254,20 @@ namespace ProjectElectricLocomotive
|
||||
openFileDialog.Title = "Загрузка";
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Загрузка из {openFileDialog.FileName} прошла успешно");
|
||||
}
|
||||
else
|
||||
catch(Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation($"Не удалось загрузить из {openFileDialog.FileName}: {ex.Message}");
|
||||
_logger.LogWarning(ex.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectElectricLocomotive
|
||||
{
|
||||
internal static class Program
|
||||
@ -8,10 +13,37 @@ namespace ProjectElectricLocomotive
|
||||
[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}serilog.json", optional: false, reloadOnChange: true
|
||||
).Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -8,6 +8,19 @@
|
||||
<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="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
|
||||
<PackageReference Include="Serilog" Version="3.1.2-dev-02097" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1-dev-00561" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.1-dev-00968" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
20
ElectricLocomotive/serilog.json
Normal file
20
ElectricLocomotive/serilog.json
Normal 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": "GasolineTanker"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user