7лаба
This commit is contained in:
parent
cb0236f1c6
commit
11cf233e44
@ -1,5 +1,6 @@
|
||||
using Lab1ContainersShip.DrawingObjects;
|
||||
using Lab1ContainersShip.MovementStrategy;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
@ -9,16 +10,19 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Lab1ContainersShip
|
||||
{
|
||||
public partial class FormShipCollection : Form
|
||||
{
|
||||
private readonly ShipGenericStorage _storage;
|
||||
public FormShipCollection()
|
||||
private readonly ILogger _logger;
|
||||
public FormShipCollection(ILogger<FormShipCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new ShipGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private void FormShipCollection_Load(object sender, EventArgs e)
|
||||
@ -48,10 +52,13 @@ namespace Lab1ContainersShip
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning("Пустое название набора");
|
||||
return;
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор: { textBoxStorageName.Text} ");
|
||||
|
||||
}
|
||||
private void ListBoxObjects_SelectedIndexChanged(object sender,EventArgs e)
|
||||
{
|
||||
@ -88,19 +95,26 @@ namespace Lab1ContainersShip
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning("Добавление пустого объекта");
|
||||
return;
|
||||
}
|
||||
|
||||
if ((obj + drawningShip) != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
_ = obj + drawningShip;
|
||||
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
|
||||
|
||||
|
||||
}
|
||||
else
|
||||
catch (ApplicationException ex)
|
||||
{
|
||||
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void ButtonRemoveCar_Click(object sender, EventArgs e)
|
||||
@ -121,14 +135,23 @@ namespace Lab1ContainersShip
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
if (obj - pos)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (ShipNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
@ -139,8 +162,7 @@ namespace Lab1ContainersShip
|
||||
{
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
|
||||
string.Empty];
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
return;
|
||||
@ -160,6 +182,7 @@ namespace Lab1ContainersShip
|
||||
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
|
||||
?? string.Empty);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удален набор: {listBoxStorages.SelectedItem}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -167,7 +190,7 @@ namespace Lab1ContainersShip
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
/*if (_storage.SaveData(saveFileDialog.FileName))
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
@ -176,6 +199,17 @@ namespace Lab1ContainersShip
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}*/
|
||||
try
|
||||
{
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -184,7 +218,7 @@ namespace Lab1ContainersShip
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
/*if (_storage.LoadData(openFileDialog.FileName))
|
||||
{
|
||||
ReloadObjects();
|
||||
MessageBox.Show("Загрузка прошла успешно",
|
||||
@ -194,8 +228,22 @@ namespace Lab1ContainersShip
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}*/
|
||||
try
|
||||
{
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
|
||||
}
|
||||
}
|
||||
ReloadObjects();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -8,9 +8,26 @@
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CSharp" Version="4.7.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.Console" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Remove="ShipCollection.resx" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Update="nlog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
</Project>
|
@ -1,8 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Lab1ContainersShip.Properties;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
|
||||
|
||||
using Serilog;
|
||||
|
||||
namespace Lab1ContainersShip
|
||||
{
|
||||
@ -11,12 +21,52 @@ namespace Lab1ContainersShip
|
||||
/// <summary>
|
||||
/// Главная точка входа для приложения.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
/*[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
Application.Run(new FormShipCollection());
|
||||
}*/
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// To customize application configuration such as set high DPIsettings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider =
|
||||
services.BuildServiceProvider())
|
||||
{
|
||||
|
||||
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
/*services.AddSingleton<FormShipCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddNLog("nlog.config");
|
||||
});*/
|
||||
services.AddSingleton<FormShipCollection>().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);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -39,7 +39,9 @@ namespace Lab1ContainersShip
|
||||
// TODO вставка в начало набора
|
||||
if(_places.Count >= _maxCount)
|
||||
{
|
||||
throw new StorageOverflowException();
|
||||
return -1;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -65,11 +67,13 @@ namespace Lab1ContainersShip
|
||||
// TODO вставка по позиции
|
||||
if(_places.Count >= _maxCount)
|
||||
{
|
||||
return false;
|
||||
// return false;
|
||||
throw new StorageOverflowException(position);
|
||||
}
|
||||
if(position < 0 || position > _places.Count)
|
||||
{
|
||||
return false;
|
||||
throw new ShipNotFoundException(position);
|
||||
//return false;
|
||||
}
|
||||
if(position == _places.Count)
|
||||
{
|
||||
@ -91,14 +95,15 @@ namespace Lab1ContainersShip
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из массива, присвоив элементу массива
|
||||
//значение null
|
||||
if(position < _places.Count && _places.Count < _maxCount)
|
||||
if(position < _places.Count)
|
||||
{
|
||||
_places[position] = null;
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
// return false;
|
||||
throw new ShipNotFoundException(position);
|
||||
}
|
||||
|
||||
}
|
||||
@ -133,9 +138,17 @@ namespace Lab1ContainersShip
|
||||
|
||||
}
|
||||
set
|
||||
{
|
||||
{
|
||||
|
||||
Insert(value, position);
|
||||
//Insert(value, position);
|
||||
try
|
||||
{
|
||||
Insert(value, position);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -111,7 +111,7 @@ DrawningObjectShip>>();
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при
|
||||
//сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -130,13 +130,13 @@ public bool SaveData(string filename)
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Невалиданя операция, нет данных для сохранения");
|
||||
}
|
||||
using(StreamWriter sr = new StreamWriter(filename))
|
||||
{
|
||||
sr.Write($"ShipStorage{Environment.NewLine}{data}");
|
||||
}
|
||||
return true;
|
||||
return;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
@ -144,22 +144,23 @@ public bool SaveData(string filename)
|
||||
/// <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 sr = new StreamReader(filename))
|
||||
{
|
||||
string str = sr.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
}
|
||||
if (!str.StartsWith("ShipStorage"))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Неверный формат данных");
|
||||
|
||||
}
|
||||
_shipStorages.Clear();
|
||||
str = sr.ReadLine();
|
||||
@ -179,16 +180,23 @@ public bool SaveData(string filename)
|
||||
elem?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (ship != null)
|
||||
{
|
||||
if (collection + ship == -1)
|
||||
/*if (collection + ship == -1)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Ошибка добавления в коллекцию");
|
||||
}*/
|
||||
try
|
||||
{
|
||||
int t = collection + ship;
|
||||
}
|
||||
catch (ApplicationException ex)
|
||||
{
|
||||
throw new Exception($"Ошибка добавления в коллекцию: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
_shipStorages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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 Lab1ContainersShip
|
||||
{
|
||||
[Serializable]
|
||||
internal class ShipNotFoundException : ApplicationException
|
||||
{
|
||||
public ShipNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
|
||||
public ShipNotFoundException() : base() { }
|
||||
public ShipNotFoundException(string message) : base(message) { }
|
||||
public ShipNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected ShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
|
||||
}
|
||||
}
|
@ -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 Lab1ContainersShip
|
||||
{
|
||||
[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) { }
|
||||
|
||||
}
|
||||
}
|
20
Lab1ContainersShip/Lab1ContainersShip/appsettings.json
Normal file
20
Lab1ContainersShip/Lab1ContainersShip/appsettings.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": "ContainerShip"
|
||||
}
|
||||
}
|
||||
}
|
13
Lab1ContainersShip/Lab1ContainersShip/nlog.config
Normal file
13
Lab1ContainersShip/Lab1ContainersShip/nlog.config
Normal 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>
|
Loading…
Reference in New Issue
Block a user