lab7 создала новые классы
This commit is contained in:
parent
0ca7d33861
commit
0931630462
@ -11,6 +11,8 @@ using System.Windows.Forms;
|
||||
using WarmlyShip.DrawingObjects;
|
||||
using WarmlyShip.Generics;
|
||||
using WarmlyShip.MovementStrategy;
|
||||
using WarmlyShip.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
|
||||
namespace WarmlyShip
|
||||
@ -25,12 +27,17 @@ namespace WarmlyShip
|
||||
/// </summary>
|
||||
private readonly ShipsGenericStorage _storage;
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormShipCollection()
|
||||
public FormShipCollection(ILogger<FormCarCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
/// <summary>
|
||||
/// Заполнение listBoxObjects
|
||||
@ -63,12 +70,13 @@ namespace WarmlyShip
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxStorageName.Text))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор: { textBoxStorageName.Text}");
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор набора
|
||||
@ -92,10 +100,13 @@ namespace WarmlyShip
|
||||
{
|
||||
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();
|
||||
_logger.LogInformation($"Удален набор: {name}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -178,6 +189,8 @@ namespace WarmlyShip
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
try
|
||||
{
|
||||
if (obj - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
@ -188,6 +201,11 @@ namespace WarmlyShip
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
catch (ShipNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Обновление рисунка по набору
|
||||
/// </summary>
|
||||
@ -216,15 +234,18 @@ namespace WarmlyShip
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
try
|
||||
{
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -237,17 +258,20 @@ namespace WarmlyShip
|
||||
{
|
||||
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);
|
||||
_logger.LogInformation("Загрузка прошла успешно");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не загрузилось: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
ReloadObjects();
|
||||
}
|
||||
}
|
||||
|
@ -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
|
||||
{
|
||||
internal static class Program
|
||||
@ -7,11 +15,38 @@ namespace WarmlyShip
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormShipCollection());
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using WarmlyShip.Exceptions;
|
||||
|
||||
namespace WarmlyShip.Generics
|
||||
{
|
||||
@ -52,11 +53,12 @@ namespace WarmlyShip.Generics
|
||||
/// <returns></returns>
|
||||
public bool Insert(T warmlyship, int position)
|
||||
{
|
||||
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_places.Insert(position, warmlyship);
|
||||
if (position < 0 || position >= _maxCount)
|
||||
throw new ShipNotFoundException(position);
|
||||
|
||||
if (Count >= _maxCount)
|
||||
throw new StorageOverflowException(position);
|
||||
_places.Insert(0, warmlyship);
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
@ -68,7 +70,7 @@ namespace WarmlyShip.Generics
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return false;
|
||||
throw new ShipNotFoundException(position);
|
||||
}
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
|
21
WarmlyShip/WarmlyShip/ShipNotFoundException.cs
Normal file
21
WarmlyShip/WarmlyShip/ShipNotFoundException.cs
Normal 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) { }
|
||||
}
|
||||
}
|
@ -98,7 +98,7 @@ namespace WarmlyShip.Generics
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -116,13 +116,12 @@ namespace WarmlyShip.Generics
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Невалиданя операция, нет данных для сохранения");
|
||||
}
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write($"ShipStorage{Environment.NewLine}{data}");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
@ -130,22 +129,23 @@ namespace WarmlyShip.Generics
|
||||
/// <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 Exception("Файл не найден");
|
||||
}
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
}
|
||||
if (!str.StartsWith("ShipStorage"))
|
||||
{
|
||||
return false;
|
||||
//если нет такой записи, то это не те данные
|
||||
throw new Exception("Неверный формат данных");
|
||||
}
|
||||
|
||||
_shipStorages.Clear();
|
||||
@ -155,7 +155,7 @@ namespace WarmlyShip.Generics
|
||||
{
|
||||
if (strs == null)
|
||||
{
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
@ -172,13 +172,13 @@ namespace WarmlyShip.Generics
|
||||
{
|
||||
if (!(collection + ship))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Ошибка добавления в коллекцию");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
_shipStorages.Add(record[0], collection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
22
WarmlyShip/WarmlyShip/StorageOverflowException.cs
Normal file
22
WarmlyShip/WarmlyShip/StorageOverflowException.cs
Normal 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) { }
|
||||
|
||||
}
|
||||
}
|
14
WarmlyShip/WarmlyShip/nlog.config
Normal file
14
WarmlyShip/WarmlyShip/nlog.config
Normal 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>
|
Loading…
Reference in New Issue
Block a user