lab7 создала новые классы

This commit is contained in:
bulatova_karina 2023-12-08 21:57:59 +03:00
parent 0ca7d33861
commit 0931630462
7 changed files with 161 additions and 43 deletions

View File

@ -11,6 +11,8 @@ using System.Windows.Forms;
using WarmlyShip.DrawingObjects; using WarmlyShip.DrawingObjects;
using WarmlyShip.Generics; using WarmlyShip.Generics;
using WarmlyShip.MovementStrategy; using WarmlyShip.MovementStrategy;
using WarmlyShip.Exceptions;
using Microsoft.Extensions.Logging;
namespace WarmlyShip namespace WarmlyShip
@ -25,12 +27,17 @@ namespace WarmlyShip
/// </summary> /// </summary>
private readonly ShipsGenericStorage _storage; private readonly ShipsGenericStorage _storage;
/// <summary> /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormShipCollection() public FormShipCollection(ILogger<FormCarCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
/// <summary> /// <summary>
/// Заполнение listBoxObjects /// Заполнение listBoxObjects
@ -63,13 +70,14 @@ namespace WarmlyShip
{ {
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
} _logger.LogInformation($"Добавлен набор: { textBoxStorageName.Text}");
}
/// <summary> /// <summary>
/// Выбор набора /// Выбор набора
/// </summary> /// </summary>
@ -92,10 +100,13 @@ namespace WarmlyShip
{ {
return; return;
} }
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); _storage.DelSet(name);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
/// <summary> /// <summary>
@ -178,14 +189,21 @@ namespace WarmlyShip
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null) try
{ {
MessageBox.Show("Объект удален"); if (obj - pos != null)
pictureBoxCollection.Image = obj.ShowShips(); {
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowShips();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
} }
else catch (ShipNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
} }
} }
/// <summary> /// <summary>
@ -216,15 +234,18 @@ namespace WarmlyShip
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
MessageBox.Show("Сохранение прошло успешно", try
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); {
} _storage.SaveData(saveFileDialog.FileName);
else MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
{ }
MessageBox.Show("Не сохранилось", "Результат", catch (Exception ex)
MessageBoxButtons.OK, MessageBoxIcon.Error); {
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} }
} }
} }
@ -237,17 +258,20 @@ namespace WarmlyShip
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", _storage.LoadData(openFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка прошла успешно");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не загрузилось: {ex.Message}");
} }
} }
ReloadObjects(); ReloadObjects();
} }
} }

View File

@ -1,3 +1,11 @@
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace WarmlyShip namespace WarmlyShip
{ {
internal static class Program internal static class Program
@ -10,8 +18,35 @@ namespace WarmlyShip
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); [STAThread]
Application.Run(new FormShipCollection()); static void Main()
{
// To customize application configuration such as set high DPI settings 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 =>
{
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);
});
}
} }
} }
} }

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WarmlyShip.Exceptions;
namespace WarmlyShip.Generics namespace WarmlyShip.Generics
{ {
@ -52,11 +53,12 @@ namespace WarmlyShip.Generics
/// <returns></returns> /// <returns></returns>
public bool Insert(T warmlyship, int position) public bool Insert(T warmlyship, int position)
{ {
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) if (position < 0 || position >= _maxCount)
{ throw new ShipNotFoundException(position);
return false;
} if (Count >= _maxCount)
_places.Insert(position, warmlyship); throw new StorageOverflowException(position);
_places.Insert(0, warmlyship);
return true; return true;
} }
/// <summary> /// <summary>
@ -68,7 +70,7 @@ namespace WarmlyShip.Generics
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return false; throw new ShipNotFoundException(position);
} }
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;

View File

@ -0,0 +1,21 @@
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

@ -98,7 +98,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))
{ {
@ -116,13 +116,12 @@ namespace WarmlyShip.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалиданя операция, нет данных для сохранения");
} }
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write($"ShipStorage{Environment.NewLine}{data}"); writer.Write($"ShipStorage{Environment.NewLine}{data}");
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по автомобилям в хранилище из файла
@ -130,22 +129,23 @@ namespace WarmlyShip.Generics
/// <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 Exception("Файл не найден");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
{ {
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (!str.StartsWith("ShipStorage")) if (!str.StartsWith("ShipStorage"))
{ {
return false; //если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
} }
_shipStorages.Clear(); _shipStorages.Clear();
@ -155,7 +155,7 @@ namespace WarmlyShip.Generics
{ {
if (strs == null) if (strs == null)
{ {
return false; return;
} }
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
@ -172,13 +172,13 @@ namespace WarmlyShip.Generics
{ {
if (!(collection + ship)) if (!(collection + ship))
{ {
return false; throw new Exception("Ошибка добавления в коллекцию");
} }
} }
} }
_shipStorages.Add(record[0], collection); _shipStorages.Add(record[0], collection);
} }
return true;
} }
} }
} }

View File

@ -0,0 +1,22 @@
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 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

@ -0,0 +1,14 @@
<?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>