lab_7 #7
19
speed_Boat/speed_Boat/BoatNotFoundException.cs
Normal file
19
speed_Boat/speed_Boat/BoatNotFoundException.cs
Normal 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 speed_Boat.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class BoatNotFoundException : ApplicationException
|
||||
{
|
||||
public BoatNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
|
||||
public BoatNotFoundException() : base() { }
|
||||
public BoatNotFoundException(string message) : base(message) { }
|
||||
public BoatNotFoundException(string message, Exception exception) : base(message, exception){ }
|
||||
protected BoatNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using speed_Boat.MovementStrategy;
|
||||
using speed_Boat.Exceptions;
|
||||
using speed_Boat.MovementStrategy;
|
||||
using SpeedBoatLab.Drawings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -52,7 +53,7 @@ namespace speed_Boat.Generics
|
||||
{
|
||||
_boatStorages = new Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
|
||||
_pictureWidth = pictureWidth;
|
||||
_pictureHeight = pictureHeight;
|
||||
_pictureHeight = pictureHeight;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -60,8 +61,11 @@ namespace speed_Boat.Generics
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_boatStorages.Count == 0)
|
||||
throw new InvalidOperationException("Невалидная операция: нет данных для сохранения");
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
@ -76,41 +80,33 @@ namespace speed_Boat.Generics
|
||||
}
|
||||
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
using (StreamWriter sw = new (filename))
|
||||
|
||||
using (StreamWriter sw = new(filename))
|
||||
{
|
||||
sw.WriteLine($"BoatStorage{Environment.NewLine}{data}");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по катерам в хранилище из файла
|
||||
/// </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 FileNotFoundException("Файл не найден");
|
||||
|
||||
string bufferTextFromFile = "";
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
if (sr.ReadLine() != "BoatStorage")
|
||||
throw new FormatException("Неверный формат данных");
|
||||
|
||||
string str = sr.ReadLine();
|
||||
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs == null || strs.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!strs[0].StartsWith("BoatStorage"))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
}
|
||||
_boatStorages.Clear();
|
||||
do
|
||||
@ -132,7 +128,7 @@ namespace speed_Boat.Generics
|
||||
{
|
||||
if (!(collection + boat))
|
||||
{
|
||||
return false;
|
||||
throw new StorageOverflowException("Ошибка добавления в коллекцию");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -140,7 +136,6 @@ namespace speed_Boat.Generics
|
||||
str = sr.ReadLine();
|
||||
} while (str != null);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@ -176,15 +171,15 @@ namespace speed_Boat.Generics
|
||||
/// </summary>
|
||||
/// <param name="ind"></param>
|
||||
/// <returns></returns>
|
||||
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>?this[string ind]
|
||||
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>? this[string ind]
|
||||
{
|
||||
get
|
||||
{
|
||||
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> boat;
|
||||
//проверка есть ли в словаре обьект с ключом ind
|
||||
if (_boatStorages.TryGetValue(ind, out boat))
|
||||
{
|
||||
return boat;
|
||||
{
|
||||
return boat;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
@ -11,6 +11,8 @@ using SpeedBoatLab.Drawings;
|
||||
using speed_Boat.Generics;
|
||||
using speed_Boat.MovementStrategy;
|
||||
using speed_Boat;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
|
||||
namespace SpeedBoatLab
|
||||
{
|
||||
@ -20,13 +22,21 @@ namespace SpeedBoatLab
|
||||
/// Набор объектов
|
||||
/// </summary>
|
||||
private readonly BoatsGenericStorage _storage;
|
||||
|
||||
/// <summary>
|
||||
/// Логгер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormBoatCollection()
|
||||
public FormBoatCollection(ILogger<FormBoatCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
|
||||
}
|
||||
///<summary>
|
||||
/// Заполнение collectionsListBox
|
||||
@ -64,10 +74,13 @@ namespace SpeedBoatLab
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не все данные заполнены:{nameStorageTextBox.Name}");
|
||||
return;
|
||||
}
|
||||
_storage.AddSet(nameStorageTextBox.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор:{nameStorageTextBox.Text}");
|
||||
|
||||
}
|
||||
///<summary>
|
||||
/// Выбор набора
|
||||
@ -86,11 +99,15 @@ namespace SpeedBoatLab
|
||||
{
|
||||
return;
|
||||
}
|
||||
string name = storagesListBox.SelectedItem.ToString() ?? string.Empty;
|
||||
|
||||
if (MessageBox.Show($"Удалить объект {storagesListBox.SelectedItem}?",
|
||||
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(storagesListBox.SelectedItem.ToString() ?? string.Empty);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удален набор: {name}");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -121,11 +138,13 @@ namespace SpeedBoatLab
|
||||
if (obj + boat)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Объект добавлен:{obj}");
|
||||
pictureBoxCollection.Image = obj.ShowBoats();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogInformation($"Не удалось добавить объект:{obj}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -155,7 +174,10 @@ namespace SpeedBoatLab
|
||||
{
|
||||
int.TryParse(insertPosition, out pos);
|
||||
if (pos < 0 || pos > obj._collection.Count - 1)
|
||||
{
|
||||
MessageBox.Show("Неверный формат позиции");
|
||||
_logger.LogWarning($"Неверный формат позиции:{pos}");
|
||||
}
|
||||
|
||||
if (obj - pos != null)
|
||||
{
|
||||
@ -166,10 +188,12 @@ namespace SpeedBoatLab
|
||||
else if (insertPosition == string.Empty)
|
||||
{
|
||||
MessageBox.Show("Неверный формат позиции");
|
||||
_logger.LogWarning($"Неверный формат позиции:{insertPosition}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning($"Не удалось удалить объект:{obj}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -201,16 +225,21 @@ namespace SpeedBoatLab
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Сохранение прошло успешно:");
|
||||
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не сохранилось:{ex.Message}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -219,16 +248,17 @@ namespace SpeedBoatLab
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storage.LoadData(saveFileDialog.FileName);
|
||||
ReloadObjects();
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не удалось загрузить: {ex.Message}",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -5,6 +5,7 @@ using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using speed_Boat.Exceptions;
|
||||
|
||||
namespace speed_Boat.Generics
|
||||
{
|
||||
@ -54,8 +55,11 @@ namespace speed_Boat.Generics
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new StorageOverflowException();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление объекта в набор на конкретную позицию.
|
||||
@ -87,7 +91,10 @@ namespace speed_Boat.Generics
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
else
|
||||
{
|
||||
throw new StorageOverflowException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -97,7 +104,12 @@ namespace speed_Boat.Generics
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return false;
|
||||
return false;
|
||||
throw new BoatNotFoundException();
|
||||
}
|
||||
if (_places[position] == null)
|
||||
{
|
||||
throw new BoatNotFoundException();
|
||||
}
|
||||
_places[position] = null;
|
||||
return true;
|
||||
|
@ -1,23 +1,46 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using System.IO;
|
||||
|
||||
|
||||
namespace SpeedBoatLab
|
||||
{
|
||||
static class Program
|
||||
{
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
Application.SetHighDpiMode(HighDpiMode.SystemAware);
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
Application.Run(new FormBoatCollection());
|
||||
ApplicationConfiguration.Initialize();
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormBoatCollection>().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);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
19
speed_Boat/speed_Boat/StorageOverflowException.cs
Normal file
19
speed_Boat/speed_Boat/StorageOverflowException.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 speed_Boat.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) { }
|
||||
}
|
||||
}
|
13
speed_Boat/speed_Boat/nlog.config
Normal file
13
speed_Boat/speed_Boat/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>
|
@ -2,10 +2,21 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<TargetFramework>net7.0-windows</TargetFramework>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
</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" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
Loading…
Reference in New Issue
Block a user
файл не используется