PIbd-23. Zakharov R.A. Lab work 07 #7
@ -1,5 +1,6 @@
|
||||
using ProjectBattleship.DrawingObjects;
|
||||
using ProjectBattleship.Generics;
|
||||
using ProjectBattleship.Exceptions;
|
||||
using ProjectBattleship.MovementStrategy;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -10,6 +11,9 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Xml.Linq;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
@ -65,6 +69,7 @@ namespace ProjectBattleship
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор набора
|
||||
@ -89,8 +94,10 @@ namespace ProjectBattleship
|
||||
}
|
||||
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();
|
||||
Log.Information($"Удален набор: {name}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -113,14 +120,17 @@ namespace ProjectBattleship
|
||||
form.Show();
|
||||
Action<DrawingShip> shipDelegate = new((ship) =>
|
||||
{
|
||||
if (obj + ship)
|
||||
try
|
||||
{
|
||||
bool q = obj + ship;
|
||||
MessageBox.Show("Объект добавлен");
|
||||
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
}
|
||||
else
|
||||
catch (StorageOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
});
|
||||
form.AddEvent(shipDelegate);
|
||||
@ -145,15 +155,23 @@ namespace ProjectBattleship
|
||||
{
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
var result = obj - pos;
|
||||
MessageBox.Show("Объект удален");
|
||||
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
}
|
||||
else
|
||||
catch (ShipNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
Log.Warning($"Было введено не число");
|
||||
MessageBox.Show("Введите число");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -185,15 +203,16 @@ namespace ProjectBattleship
|
||||
{
|
||||
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);
|
||||
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
Log.Warning("Не удалось сохранить");
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -206,19 +225,21 @@ namespace ProjectBattleship
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
|
||||
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
|
||||
foreach (var collection in _storage.Keys)
|
||||
{
|
||||
listBoxStorages.Items.Add(collection);
|
||||
}
|
||||
ReloadObjects();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
Log.Warning("Не удалось загрузить");
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,16 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Serilog;
|
||||
using Serilog.Events;
|
||||
using Serilog.Formatting.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using System.IO;
|
||||
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
internal static class Program
|
||||
@ -8,9 +21,23 @@ namespace ProjectBattleship
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
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 FormShipsCollection());
|
||||
}
|
||||
}
|
||||
|
@ -8,6 +8,18 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<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.5" />
|
||||
<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>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@ -23,4 +35,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appsettings.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectBattleship.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -17,26 +18,25 @@ namespace ProjectBattleship.Generics
|
||||
_maxCount = count;
|
||||
_places = new List<T?>(count);
|
||||
}
|
||||
public bool Insert(T ship)
|
||||
public void Insert(T ship)
|
||||
{
|
||||
if (_places.Count == _maxCount)
|
||||
return false;
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
Insert(ship, 0);
|
||||
return true;
|
||||
}
|
||||
public bool Insert(T ship, int position)
|
||||
public void Insert(T ship, int position)
|
||||
{
|
||||
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
|
||||
return false;
|
||||
if (_places.Count == _maxCount)
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
if (!(position >= 0 && position < Count))
|
||||
throw new Exception("Неверная позиция для вставки");
|
||||
_places.Insert(position, ship);
|
||||
return true;
|
||||
}
|
||||
public bool Remove(int position)
|
||||
public void Remove(int position)
|
||||
{
|
||||
if (!(position >= 0 && position < Count))
|
||||
return false;
|
||||
throw new ShipNotFoundException(position);
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
public T? this[int position]
|
||||
{
|
||||
|
20
ProjectBattleship/ProjectBattleship/ShipNotFoundException.cs
Normal file
20
ProjectBattleship/ProjectBattleship/ShipNotFoundException.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
|
||||
namespace ProjectBattleship.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 context) : base(info, context) { }
|
||||
}
|
||||
}
|
@ -29,16 +29,16 @@ namespace ProjectBattleship.Generics
|
||||
public static bool operator +(ShipsGenericCollection<T, U>? collect, T? obj)
|
||||
{
|
||||
if (obj != null && collect != null)
|
||||
return collect._collection.Insert(obj);
|
||||
{
|
||||
collect._collection.Insert(obj);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public static T? operator -(ShipsGenericCollection<T, U> collect, int pos)
|
||||
{
|
||||
T? obj = collect._collection[pos];
|
||||
if (obj != null)
|
||||
{
|
||||
collect._collection.Remove(pos);
|
||||
}
|
||||
collect._collection.Remove(pos);
|
||||
return obj;
|
||||
}
|
||||
public U? GetU(int pos)
|
||||
|
@ -43,7 +43,7 @@ namespace ProjectBattleship.Generics
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -61,19 +61,18 @@ namespace ProjectBattleship.Generics
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new IOException("Невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
using (StreamWriter sw = new(filename))
|
||||
{
|
||||
sw.WriteLine($"ShipStorage{Environment.NewLine}{data}");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new IOException("Файл не найден");
|
||||
}
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
@ -81,11 +80,11 @@ namespace ProjectBattleship.Generics
|
||||
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs == null || strs.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new IOException("Нет данных для загрузки");
|
||||
}
|
||||
if (!strs[0].StartsWith("ShipStorage"))
|
||||
{
|
||||
return false;
|
||||
throw new IOException("Неверный формат данных");
|
||||
}
|
||||
_shipsStorages.Clear();
|
||||
do
|
||||
@ -106,7 +105,7 @@ namespace ProjectBattleship.Generics
|
||||
{
|
||||
if (!(collection + ship))
|
||||
{
|
||||
return false;
|
||||
throw new IOException("Ошибка добавления в коллекцию");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -114,7 +113,6 @@ namespace ProjectBattleship.Generics
|
||||
str = sr.ReadLine();
|
||||
} while (str != null);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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 ProjectBattleship.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 context) : base(info, context) { }
|
||||
}
|
||||
}
|
15
ProjectBattleship/ProjectBattleship/appsettings.json
Normal file
15
ProjectBattleship/ProjectBattleship/appsettings.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": { "path": "log.log" }
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "Sample"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user