работа 7

This commit is contained in:
bekodeg 2023-11-28 17:17:38 +04:00
parent b86d3af35e
commit 23a7a41196
8 changed files with 135 additions and 38 deletions

View 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 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) { }
}
}

View 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) { }
}
}

View File

@ -133,7 +133,7 @@ namespace ProjectElectricLocomotive.Generics
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалиданя операция, нет данных длясохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
@ -151,7 +151,7 @@ namespace ProjectElectricLocomotive.Generics
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException($"Файл {filename} не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
@ -167,12 +167,12 @@ namespace ProjectElectricLocomotive.Generics
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
throw new FileLoadException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("LocomotiveStorage"))
{
//если нет такой записи, то это не те данные
return false;
throw new ArgumentException("Неверный формат данных");
}
_locomotiveStorage.Clear();
foreach (string data in strs)
@ -197,7 +197,7 @@ namespace ProjectElectricLocomotive.Generics
{
if ((collection + locomotive) == 0)
{
return false;
throw new InvalidOperationException("Ошибкадобавления в коллекцию");
}
}
}

View File

@ -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;
@ -74,7 +75,10 @@ namespace ProjectElectricLocomotive.Generics
{
return false;
}
if (_places[position] == null)
{
throw new LocomotiveNotFoundException(position);
}
_places.RemoveAt(position);
return true;

View File

@ -1,12 +1,8 @@
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.Xml.Linq;
namespace ProjectElectricLocomotive
{
@ -21,15 +17,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 +68,7 @@ namespace ProjectElectricLocomotive
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
}
/// <summary>
@ -90,12 +92,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 +126,22 @@ 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();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
}
}
@ -165,14 +176,21 @@ 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();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (LocomotiveNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
}
}
/// <summary>
@ -205,15 +223,16 @@ 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);
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -225,16 +244,17 @@ 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();
}
else
catch(Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загрузилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ProjectElectricLocomotive
{
internal static class Program
@ -11,7 +15,20 @@ namespace ProjectElectricLocomotive
// 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 =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -8,6 +8,11 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>