правки 7 лаб
This commit is contained in:
parent
ca8a0d1118
commit
f5559ddebe
20
Tank/Tank/Exceptions/TankNotFoundException.cs
Normal file
20
Tank/Tank/Exceptions/TankNotFoundException.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
|
||||
namespace Tank.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class TankNotFoundException : ApplicationException
|
||||
{
|
||||
public TankNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
public TankNotFoundException() : base() { }
|
||||
public TankNotFoundException(string message) : base(message) { }
|
||||
public TankNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected TankNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
19
Tank/Tank/Exceptions/TankStorageOverflowException.cs
Normal file
19
Tank/Tank/Exceptions/TankStorageOverflowException.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 Tank.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class TankStorageOverflowException : ApplicationException
|
||||
{
|
||||
public TankStorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
|
||||
public TankStorageOverflowException() : base() { }
|
||||
public TankStorageOverflowException(string message) : base(message) { }
|
||||
public TankStorageOverflowException(string message, Exception exception) : base(message, exception) { }
|
||||
protected TankStorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
@ -10,12 +11,16 @@ using System.Windows.Forms;
|
||||
using Tank.DrawingObjects;
|
||||
using Tank.MovementStrategy;
|
||||
using Tank.Generics;
|
||||
using Tank.Exceptions;
|
||||
|
||||
namespace Tank
|
||||
{
|
||||
public partial class FormArmoredCarCollection : Form
|
||||
{
|
||||
private readonly TanksGenericStorage _storage;
|
||||
|
||||
// Логгер
|
||||
private readonly ILogger _logger;
|
||||
public FormArmoredCarCollection()
|
||||
{
|
||||
InitializeComponent();
|
||||
@ -48,15 +53,22 @@ namespace Tank
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning("Добавление пустого объекта");
|
||||
return;
|
||||
}
|
||||
if ((obj + tank) != false)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowTanks();
|
||||
if ((obj + tank) != false)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowTanks();
|
||||
_logger.LogInformation($"Добавлен объект {obj}");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (TankStorageOverflowException ex)
|
||||
{
|
||||
_logger.LogWarning($"{ex.Message} в {listBoxStorages.SelectedItem.ToString()}");
|
||||
MessageBox.Show(ex.Message);
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
@ -80,6 +92,7 @@ namespace Tank
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Удаление объекта из несуществующего набора");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
@ -90,17 +103,28 @@ namespace Tank
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
_logger.LogWarning("Отмена удаления объекта");
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowTanks();
|
||||
if (obj - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Удален объект с позиции{pos}");
|
||||
pictureBoxCollection.Image = obj.ShowTanks();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (TankNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"{ex.Message} из {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
}
|
||||
public void RefreshCollection()
|
||||
@ -136,14 +160,18 @@ namespace Tank
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Удаление невыбранного набора");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show($"Удалить объект { listBoxStorages.SelectedItem}?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
|
||||
string nameSet = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
|
||||
if (MessageBox.Show($"Удалить объект {nameSet}?", "Удаление", MessageBoxButtons.YesNo,
|
||||
MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(nameSet);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Набор '{nameSet}' удален");
|
||||
}
|
||||
_logger.LogWarning("Отмена удаления набора");
|
||||
}
|
||||
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
@ -154,15 +182,16 @@ namespace Tank
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_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.Information);
|
||||
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -171,14 +200,17 @@ namespace Tank
|
||||
{
|
||||
if (openFileDialog1.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog1.FileName))
|
||||
try
|
||||
{
|
||||
_storage.LoadData(openFileDialog1.FileName);
|
||||
ReloadObjects();
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Данные загружены из файла {openFileDialog1.FileName}");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ using Tank.MovementStrategy;
|
||||
using System.Globalization;
|
||||
using Tank.Drawings;
|
||||
using System.Xml.Linq;
|
||||
using Tank.Exceptions;
|
||||
|
||||
namespace Tank.Generics
|
||||
{
|
||||
@ -105,7 +106,7 @@ namespace Tank.Generics
|
||||
}
|
||||
}
|
||||
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -124,13 +125,12 @@ namespace Tank.Generics
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Невалиданя операция, нет данных для сохранения");
|
||||
}
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.WriteLine("TankStorage");
|
||||
writer.Write(data.ToString());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public bool SaveCollection(string filename)
|
||||
@ -166,45 +166,57 @@ namespace Tank.Generics
|
||||
/// </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 Exception("Файл не найден");
|
||||
}
|
||||
using (StreamReader reader = new StreamReader(filename))
|
||||
{
|
||||
string strCheck = reader.ReadLine();
|
||||
if (!strCheck.StartsWith("TankStorage"))
|
||||
return false;
|
||||
_tankStorages.Clear();
|
||||
string Str;
|
||||
while ((Str = reader.ReadLine()) != null)
|
||||
string checker = reader.ReadLine();
|
||||
if (checker == null)
|
||||
throw new NullReferenceException("Нет данных для загрузки");
|
||||
if (!checker.StartsWith("TankStorage"))
|
||||
{
|
||||
if (Str == null)
|
||||
throw new FormatException("Неверный формат данных");
|
||||
}
|
||||
_tankStorages.Clear();
|
||||
string strs;
|
||||
bool firstinit = true;
|
||||
while ((strs = reader.ReadLine()) != null)
|
||||
{
|
||||
if (strs == null && firstinit)
|
||||
throw new NullReferenceException("Нет данных для загрузки");
|
||||
if (strs == null)
|
||||
break;
|
||||
string name = Str.Split('|')[0];
|
||||
firstinit = false;
|
||||
string name = strs.Split('|')[0];
|
||||
TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar> collection = new(_pictureWidth, _pictureHeight);
|
||||
foreach (string data in Str.Split('|')[1].Split(';'))
|
||||
foreach (string data in strs.Split('|')[1].Split(';'))
|
||||
{
|
||||
DrawingArmoredCar? ArmoredCar = data?.CreateDrawTank(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (ArmoredCar != null)
|
||||
{
|
||||
if (!(collection + ArmoredCar))
|
||||
try
|
||||
{
|
||||
return false;
|
||||
_ = collection + ArmoredCar;
|
||||
}
|
||||
catch (TankNotFoundException e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
catch (TankStorageOverflowException e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
_tankStorages.Add(name, collection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -1,3 +1,28 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.VisualBasic.Logging;
|
||||
using Serilog;
|
||||
using Serilog.Events;
|
||||
using Serilog.Formatting.Json;
|
||||
using Log = Serilog.Log;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Serilog.Core;
|
||||
using Serilog.Events;
|
||||
using Serilog.Formatting.Json;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace Tank
|
||||
{
|
||||
internal static class Program
|
||||
@ -8,10 +33,31 @@ namespace Tank
|
||||
[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 FormArmoredCarCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormArmoredCarCollection>());
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormArmoredCarCollection>().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}appSetting.json", optional: false, reloadOnChange: true).Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -27,4 +27,19 @@
|
||||
<Folder Include="MovementStrategy\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DependencyInjection.AutoRegistration" Version="3.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
20
Tank/Tank/appSetting.json
Normal file
20
Tank/Tank/appSetting.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": "Tank"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user