PIbd-21 Malafeev L.S. CruiserBase Lab7 #9
@ -23,4 +23,16 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" 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="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>
|
19
Cruiser/Exceptions/CruiserNotFoundException.cs
Normal file
19
Cruiser/Exceptions/CruiserNotFoundException.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 Cruiser.Exceptions
|
||||
{
|
||||
internal class CruiserNotFoundException : ApplicationException
|
||||
{
|
||||
public CruiserNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
|
||||
public CruiserNotFoundException() : base() { }
|
||||
public CruiserNotFoundException(string message) : base(message) { }
|
||||
public CruiserNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected CruiserNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
|
||||
}
|
20
Cruiser/Exceptions/StorageOverflowException.cs
Normal file
20
Cruiser/Exceptions/StorageOverflowException.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 Cruiser.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) { }
|
||||
}
|
||||
|
||||
}
|
4
Cruiser/FormCruiserCollection.Designer.cs
generated
4
Cruiser/FormCruiserCollection.Designer.cs
generated
@ -177,14 +177,14 @@
|
||||
// SaveToolStripMenuItem
|
||||
//
|
||||
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
|
||||
SaveToolStripMenuItem.Size = new Size(180, 22);
|
||||
SaveToolStripMenuItem.Size = new Size(133, 22);
|
||||
SaveToolStripMenuItem.Text = "Сохранить";
|
||||
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
|
||||
//
|
||||
// UploadToolStripMenuItem
|
||||
//
|
||||
UploadToolStripMenuItem.Name = "UploadToolStripMenuItem";
|
||||
UploadToolStripMenuItem.Size = new Size(180, 22);
|
||||
UploadToolStripMenuItem.Size = new Size(133, 22);
|
||||
UploadToolStripMenuItem.Text = "Загрузить";
|
||||
UploadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
|
||||
//
|
||||
|
@ -11,6 +11,9 @@ using System.Windows.Forms;
|
||||
using Cruiser.Drawing;
|
||||
using Cruiser.Generics;
|
||||
using Cruiser.MovementStrategy;
|
||||
using Cruiser.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Cruiser
|
||||
{
|
||||
@ -24,12 +27,17 @@ namespace Cruiser
|
||||
/// </summary>
|
||||
private readonly CruisersGenericStorage _storage;
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormCruiserCollection()
|
||||
public FormCruiserCollection(ILogger<FormCruiserCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new CruisersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
/// <summary>
|
||||
/// Заполнение listBoxObjects
|
||||
@ -65,6 +73,7 @@ namespace Cruiser
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление набора
|
||||
@ -79,8 +88,10 @@ namespace Cruiser
|
||||
}
|
||||
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
|
||||
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; //добавил для удаления повторяющегося кода
|
||||
_storage.DelSet(name);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удален набор: {name}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -105,21 +116,31 @@ namespace Cruiser
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Добавление круизера не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Добавление круизера не удалось (нет хранилища)");
|
||||
return;
|
||||
}
|
||||
if ((obj + cruiser))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowCruiser();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
if ((obj + cruiser))
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Добавление круизера успешно {listBoxStorages.SelectedItem.ToString()}");
|
||||
pictureBoxCollection.Image = obj.ShowCruiser();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
catch (ApplicationException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -131,28 +152,42 @@ namespace Cruiser
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Удаление круизера не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Удаление круизера не удалось (нет хранилища)");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
_logger.LogWarning($"Удаление круизера не удалось (выбран вариант 'Нет')");
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(textBoxNumber.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowCruiser();
|
||||
}
|
||||
else
|
||||
if (obj - pos != null)
|
||||
{
|
||||
_logger.LogInformation($"Удаление круизера успешно {listBoxStorages.SelectedItem.ToString()} {pos}");
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowCruiser();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning($"Удаление круизера не удалось(обьект не найден)");
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
catch (CruiserNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning($"Удаление круизера не удалось {ex.Message}");
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Обновление рисунка по набору
|
||||
|
@ -128,20 +128,16 @@ namespace Cruiser.Generics
|
||||
{
|
||||
int Ix = 0;
|
||||
int Iy = 0;
|
||||
int i = 0;
|
||||
foreach (var cruiser in _collection.GetCruisers())
|
||||
{
|
||||
cruiser._pictureHeight = _pictureHeight;// добавил для починки отрисовки на форме коллекций
|
||||
cruiser._pictureWidth = _pictureWidth;// добавил для починки отрисовки на форме коллекций
|
||||
_collection[i]?.SetPosition(Ix, Iy);
|
||||
_collection[i]?.DrawTransport(g);
|
||||
cruiser?.SetPosition(Ix, Iy); // починил, для починки удаления
|
||||
cruiser?.DrawTransport(g);
|
||||
Ix += _placeSizeWidth;
|
||||
if (Ix + _placeSizeHeight > _pictureWidth)
|
||||
{
|
||||
Ix = 0;
|
||||
Iy = _placeSizeHeight;
|
||||
Iy += _placeSizeHeight; // починил, т.к. отрисовывалось максимум 8 кораблей
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,6 +5,7 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Cruiser.Drawing;
|
||||
using Cruiser.MovementStrategy;
|
||||
using System.IO;
|
||||
|
||||
namespace Cruiser.Generics
|
||||
{
|
||||
@ -105,7 +106,7 @@ namespace Cruiser.Generics
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Невалиданя операция, нет данных для сохранения");
|
||||
}
|
||||
string dataStr = data.ToString();
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
@ -124,18 +125,18 @@ namespace Cruiser.Generics
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
using (StreamReader reader = new StreamReader(filename))
|
||||
{
|
||||
string checker = reader.ReadLine();
|
||||
if (checker == null)
|
||||
{
|
||||
return false;
|
||||
throw new NullReferenceException("Нет данных для загрузки");
|
||||
}
|
||||
if (!checker.StartsWith("CruiserStorage"))
|
||||
{
|
||||
return false;
|
||||
throw new FormatException("Неверный формат данных");
|
||||
}
|
||||
_cruiserStorages.Clear();
|
||||
string strs;
|
||||
@ -156,9 +157,13 @@ namespace Cruiser.Generics
|
||||
DrawingCruiser? cruiser = data?.CreateDrawingCruiser(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (cruiser != null)
|
||||
{
|
||||
if (collection + cruiser == false)
|
||||
try
|
||||
{
|
||||
return false;
|
||||
bool? tmp = collection + cruiser;
|
||||
}
|
||||
catch (ApplicationException ex)
|
||||
{
|
||||
throw new ApplicationException($"Ошибка добавления в коллекцию: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Cruiser.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Eventing.Reader;
|
||||
using System.Linq;
|
||||
@ -40,12 +41,13 @@ namespace Cruiser.Generics
|
||||
/// </summary>
|
||||
/// <param name="cruiser">Добавляемый лайнер</param>
|
||||
/// <returns></returns>
|
||||
public bool Insert(T cruiser)
|
||||
public bool Insert(T cruiser) //починил код, работал неправильно
|
||||
{
|
||||
if (_places.Count + 1 <= _maxCount)
|
||||
if (_places.Count >= _maxCount)
|
||||
{
|
||||
_places.Insert(0, cruiser);
|
||||
throw new StorageOverflowException(_places.Count);
|
||||
}
|
||||
_places.Insert(0, cruiser);
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
@ -57,7 +59,7 @@ namespace Cruiser.Generics
|
||||
{
|
||||
if (position < 0 || position > _places.Count)
|
||||
{
|
||||
return false;
|
||||
throw new CruiserNotFoundException(position);
|
||||
}
|
||||
_places[position] = null;
|
||||
return true;
|
||||
@ -68,14 +70,18 @@ namespace Cruiser.Generics
|
||||
/// <param name="cruiser">Добавляемый автомобиль</param>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns></returns>
|
||||
public bool Insert(T cruiser, int position)
|
||||
public bool Insert(T cruiser, int position) //починил код, работал неправильно
|
||||
{
|
||||
if (_places.Count + 1 <= _maxCount && _places.Count >= position)
|
||||
if (_places.Count >= _maxCount)
|
||||
{
|
||||
_places.Insert(position, cruiser);
|
||||
return true;
|
||||
throw new StorageOverflowException(_places.Count);
|
||||
}
|
||||
return false;
|
||||
if (position < 0 || position > _places.Count)
|
||||
{
|
||||
throw new CruiserNotFoundException(position);
|
||||
}
|
||||
_places.Insert(position, cruiser);
|
||||
return true;
|
||||
}
|
||||
public T? this[int position]
|
||||
{
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace Cruiser
|
||||
{
|
||||
internal static class Program
|
||||
@ -10,8 +15,32 @@ namespace Cruiser
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormCruiserCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormCruiserCollection>());
|
||||
}
|
||||
static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormCruiserCollection>().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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
20
Cruiser/appsettings.json
Normal file
20
Cruiser/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": "Cruiser"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user