This commit is contained in:
Dasha 2023-12-26 23:00:14 +04:00
parent 44df2f7cac
commit 3e75f73a19
10 changed files with 169 additions and 49 deletions

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace WarmlyShip.Exceptions
{
[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) { }
}
}

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 WarmlyShip.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

@ -10,6 +10,10 @@ using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using WarmlyShip.DrawningObjects; using WarmlyShip.DrawningObjects;
using WarmlyShip.MovementStrategy; using WarmlyShip.MovementStrategy;
using Microsoft.Extensions.Logging;
using WarmlyShip.Exceptions;
using System.Xml.Linq;
using Serilog;
namespace WarmlyShip namespace WarmlyShip
{ {
@ -70,6 +74,7 @@ namespace WarmlyShip
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
} }
/// <summary> /// <summary>
@ -96,9 +101,10 @@ namespace WarmlyShip
if (MessageBox.Show($"Удалить объект {ListBoxObjects.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, if (MessageBox.Show($"Удалить объект {ListBoxObjects.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(ListBoxObjects.SelectedItem.ToString() string name = (ListBoxObjects.SelectedItem.ToString() ?? string.Empty);
?? string.Empty); _storage.DelSet(name);
ReloadObjects(); ReloadObjects();
Log.Information($"Удален набор: {name}");
} }
} }
@ -121,18 +127,20 @@ namespace WarmlyShip
FormShipConfig form = new(); FormShipConfig form = new();
form.Show(); form.Show();
Action<DrawningShip>? shipDelegate = new((m) => Action<DrawningShip>? shipDelegate = new((ship) =>
{ {
bool isAdditionSuccessful = (obj + m); try
if (isAdditionSuccessful)
{ {
bool isAdditionSuccessful = obj + ship;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); ship.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
Log.Information($"Добавлен объект в коллекцию {ListBoxObjects.SelectedItem.ToString() ?? string.Empty}");
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); Log.Warning($"Коллекция {ListBoxObjects.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
} }
}); });
form.AddEvent(shipDelegate); form.AddEvent(shipDelegate);
@ -160,15 +168,23 @@ namespace WarmlyShip
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); try
if (obj - pos != null)
{ {
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var isAdditionSuccessful = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {ListBoxObjects.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
} }
else catch (ShipNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); Log.Warning($"Не получилось удалить объект из коллекции {ListBoxObjects.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
} }
} }
@ -201,13 +217,16 @@ namespace WarmlyShip
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@ -221,17 +240,21 @@ namespace WarmlyShip
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys) foreach (var collection in _storage.Keys)
{ {
ListBoxObjects.Items.Add(collection); ListBoxObjects.Items.Add(collection);
} }
ReloadObjects();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using WarmlyShip.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -43,15 +44,14 @@ namespace WarmlyShip.Generics
/// </summary> /// </summary>
/// <param name="ship">Добавляемый корабль</param> /// <param name="ship">Добавляемый корабль</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T ship) public void Insert(T ship)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
{ {
return false; throw new StorageOverflowException(_maxCount);
} }
Insert(ship, 0); Insert(ship, 0);
return true;
} }
/// <summary> /// <summary>
@ -60,15 +60,18 @@ namespace WarmlyShip.Generics
/// <param name="ship">Добавляемый корабль</param> /// <param name="ship">Добавляемый корабль</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T ship, int position) public void Insert(T ship, int position)
{ {
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) if (_places.Count == _maxCount)
{ {
return false; throw new StorageOverflowException(_maxCount);
}
if (!(position >= 0 && position <= Count))
{
throw new Exception("Неверная позиция для вставки");
} }
_places.Insert(position, ship); _places.Insert(position, ship);
return true;
} }
/// <summary> /// <summary>
@ -76,15 +79,14 @@ namespace WarmlyShip.Generics
/// </summary> /// </summary>
/// <param name="position"></param> /// <param name="position"></param>
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public void Remove(int position)
{ {
if (position < 0 || position >= Count) if (!(position >= 0 && position < Count))
{ {
return false; throw new ShipNotFoundException(position);
} }
_places.RemoveAt(position); _places.RemoveAt(position);
return true;
} }
/// <summary> /// <summary>
@ -96,7 +98,7 @@ namespace WarmlyShip.Generics
{ {
get get
{ {
if (position < 0 || position >= _maxCount) if (!(position >= 0 && position < Count))
{ {
return null; return null;
} }
@ -110,7 +112,6 @@ namespace WarmlyShip.Generics
} }
_places.Insert(position, value); _places.Insert(position, value);
return;
} }
} }

View File

@ -70,11 +70,12 @@ namespace WarmlyShip.Generics
/// <returns></returns> /// <returns></returns>
public static bool operator +(ShipsGenericCollection<T, U> collect, T? obj) public static bool operator +(ShipsGenericCollection<T, U> collect, T? obj)
{ {
if (obj == null) if (obj == null || collect == null)
{ {
return false; return false;
} }
return collect?._collection.Insert(obj) ?? false; collect?._collection.Insert(obj);
return true;
} }
/// <summary> /// <summary>
@ -86,10 +87,7 @@ namespace WarmlyShip.Generics
public static T? operator -(ShipsGenericCollection<T, U> collect, int pos) public static T? operator -(ShipsGenericCollection<T, U> collect, int pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos); collect._collection.Remove(pos);
}
return obj; return obj;
} }

View File

@ -64,7 +64,7 @@ namespace WarmlyShip.Generics
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -83,7 +83,7 @@ namespace WarmlyShip.Generics
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new IOException("Невалидная операция, нет данных для сохранения");
} }
string toWrite = $"ShipStorage{Environment.NewLine}{data}"; string toWrite = $"ShipStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
@ -95,7 +95,6 @@ namespace WarmlyShip.Generics
sw.WriteLine(str); sw.WriteLine(str);
} }
} }
return true;
} }
/// <summary> /// <summary>
@ -103,11 +102,11 @@ namespace WarmlyShip.Generics
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new IOException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
@ -115,11 +114,11 @@ namespace WarmlyShip.Generics
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
return false; throw new IOException("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("ShipStorage")) if (!strs[0].StartsWith("ShipStorage"))
{ {
return false; throw new IOException("Неверный формат данных");
} }
_shipStorages.Clear(); _shipStorages.Clear();
do do
@ -140,7 +139,7 @@ namespace WarmlyShip.Generics
{ {
if (!(collection + ship)) if (!(collection + ship))
{ {
return false; throw new IOException("Ошибка добавления в коллекцию");
} }
} }
} }
@ -149,7 +148,6 @@ namespace WarmlyShip.Generics
str = sr.ReadLine(); str = sr.ReadLine();
} while (str != null); } while (str != null);
} }
return true;
} }
/// <summary> /// <summary>

View File

@ -1,3 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace WarmlyShip namespace WarmlyShip
{ {
internal static class Program internal static class Program
@ -8,9 +16,23 @@ namespace WarmlyShip
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
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();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormShipCollection()); Application.Run(new FormShipCollection());
} }
} }

View File

@ -12,4 +12,16 @@
<Folder Include="Resources\" /> <Folder Include="Resources\" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<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="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> </Project>

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}

13
WarmlyShip/nlog.config Normal file
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>