PIBD-12_Morozov_D.V. LabWork№7 #18
@ -1,4 +1,5 @@
|
||||
using ProjectContainerShip.Drawnings;
|
||||
using ProjectContainerShip.Exceptions;
|
||||
|
||||
namespace ProjectContainerShip.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
@ -34,7 +35,7 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@ -72,6 +73,7 @@ public abstract class AbstractCompany
|
||||
return company._collection?.Remove(position) ?? null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получение случайного объекта из коллекции
|
||||
/// </summary>
|
||||
@ -95,8 +97,12 @@ public abstract class AbstractCompany
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawningShip? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawningShip? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectContainerShip.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -49,45 +50,37 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= 0 && position < Count)
|
||||
{
|
||||
return _collection[position];
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count == _maxCount) { return -1; }
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position < 0 || position >= Count || Count == _maxCount)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
_collection.Insert(position, obj);
|
||||
if (position < 0 || position >= Count)
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (Count == _maxCount)
|
||||
throw new CollectionOverflowException(Count);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position >= Count || position < 0) return null;
|
||||
T? obj = _collection[position];
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Count; ++i)
|
||||
{
|
||||
|
@ -1,4 +1,6 @@
|
||||
namespace ProjectContainerShip.CollectionGenericObjects;
|
||||
using ProjectContainerShip.Exceptions;
|
||||
|
||||
namespace ProjectContainerShip.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
@ -48,24 +50,29 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= 0 && position < Count)
|
||||
{
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
return null;
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
return Insert(obj, 0);
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return -1;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
@ -90,15 +97,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return null;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
T obj = _collection[position];
|
||||
_collection[position] = null;
|
||||
return obj;
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectContainerShip.Drawnings;
|
||||
using ProjectContainerShip.Exceptions;
|
||||
|
||||
namespace ProjectContainerShip.CollectionGenericObjects;
|
||||
|
||||
@ -18,6 +19,11 @@ public class ShipSharingService : AbstractCompany
|
||||
|
||||
protected override void DrawBackground(Graphics g)
|
||||
{
|
||||
Color backgroundColor = Color.SkyBlue;
|
||||
using (Brush brush = new SolidBrush(backgroundColor))
|
||||
{
|
||||
g.FillRectangle(brush, new Rectangle(0, 0, _pictureWidth, _pictureHeight));
|
||||
}
|
||||
Pen pen = new Pen(Color.Brown, 3);
|
||||
int offsetX = 10, offsetY = -12;
|
||||
int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY;
|
||||
@ -29,7 +35,7 @@ public class ShipSharingService : AbstractCompany
|
||||
{
|
||||
numCols++;
|
||||
g.DrawLine(pen, x, y, x + _placeSizeWidth / 2, y);
|
||||
g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 8);
|
||||
g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 4);
|
||||
locCoord.Add(new Tuple<int, int>(x, y));
|
||||
x += _placeSizeWidth + 2;
|
||||
}
|
||||
@ -48,8 +54,12 @@ public class ShipSharingService : AbstractCompany
|
||||
int row = numRows - 1, col = numCols;
|
||||
for (int i = 0; i < _collection?.Count; i++, col--)
|
||||
{
|
||||
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
|
||||
try
|
||||
{
|
||||
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
|
||||
}
|
||||
catch (Exception) { }
|
||||
if (col == 1)
|
||||
{
|
||||
col = numCols + 1;
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectContainerShip.Drawnings;
|
||||
using ProjectContainerShip.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -109,11 +110,11 @@ public class StorageCollection<T>
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
@ -149,27 +150,28 @@ public class StorageCollection<T>
|
||||
sb.Clear();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
/// <summary>
|
||||
/// Загрузка информации по кораблям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader sr = new StreamReader(filename))
|
||||
{
|
||||
string? str;
|
||||
str = sr.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
throw new Exception("В файле нет данных");
|
||||
if (str != _collectionKey.ToString())
|
||||
return false;
|
||||
throw new Exception("В файле неверные данные");
|
||||
_storages.Clear();
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
{
|
||||
@ -182,7 +184,7 @@ public class StorageCollection<T>
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
@ -192,15 +194,20 @@ public class StorageCollection<T>
|
||||
{
|
||||
if (elem?.CreateDrawningShip() is T boat)
|
||||
{
|
||||
if (collection.Insert(boat) == -1)
|
||||
return false;
|
||||
try
|
||||
{
|
||||
if (collection.Insert(boat) == -1)
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectContainerShip.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class CollectionOverflowException : ApplicationException
|
||||
{
|
||||
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
|
||||
public CollectionOverflowException() : base() { }
|
||||
public CollectionOverflowException(string message) : base(message) { }
|
||||
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
|
||||
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectContainerShip.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class ObjectNotFoundException : ApplicationException
|
||||
{
|
||||
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
|
||||
public ObjectNotFoundException() : base() { }
|
||||
public ObjectNotFoundException(string message) : base(message) { }
|
||||
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectContainerShip.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку выхода за границы коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class PositionOutOfCollectionException : ApplicationException
|
||||
{
|
||||
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
|
||||
public PositionOutOfCollectionException() : base() { }
|
||||
public PositionOutOfCollectionException(string message) : base(message) { }
|
||||
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
|
||||
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -1,6 +1,8 @@
|
||||
using ProjectContainerShip.CollectionGenericObjects;
|
||||
using ProjectContainerShip.Drawnings;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectContainerShip.Exceptions;
|
||||
|
||||
|
||||
namespace ProjectContainerShip
|
||||
@ -20,15 +22,23 @@ namespace ProjectContainerShip
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawningShip> _storageCollection;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormShipCollection()
|
||||
public FormShipCollection(ILogger<FormShipCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
#region Работа с компанией
|
||||
/// <summary>
|
||||
/// Выбор компании
|
||||
/// </summary>
|
||||
@ -59,19 +69,25 @@ namespace ProjectContainerShip
|
||||
/// <param name="boat"></param>
|
||||
private void SetShip(DrawningShip? ship)
|
||||
{
|
||||
if (_company == null || ship == null)
|
||||
try
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (_company == null || ship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + ship != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (_company + ship != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Добавлен объект: " + ship.GetDataForSave());
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (ObjectNotFoundException) { }
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show("В коллекции превышено допустимое количество элементов");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -82,25 +98,31 @@ namespace ProjectContainerShip
|
||||
/// <param name="e"></param>
|
||||
private void ButtonDelShip_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_company - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
|
||||
{
|
||||
throw new Exception("Входные данные отсутствуют");
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Объект удален");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show("Не найден объект по позиции " + pos);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -118,24 +140,32 @@ namespace ProjectContainerShip
|
||||
|
||||
DrawningShip? ship = null;
|
||||
int counter = 100;
|
||||
while (ship == null)
|
||||
try
|
||||
{
|
||||
ship = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
while (ship == null)
|
||||
{
|
||||
break;
|
||||
ship = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (ship == null)
|
||||
if (ship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
FormContainerShip form = new FormContainerShip();
|
||||
form.SetShip = ship;
|
||||
form.ShowDialog();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return;
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
|
||||
FormContainerShip form = new FormContainerShip();
|
||||
form.SetShip = ship;
|
||||
form.ShowDialog();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -152,7 +182,8 @@ namespace ProjectContainerShip
|
||||
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
|
||||
#endregion
|
||||
#region Работа с коллекцией
|
||||
/// <summary>
|
||||
/// Добавление коллекции
|
||||
/// </summary>
|
||||
@ -163,6 +194,7 @@ namespace ProjectContainerShip
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
|
||||
return;
|
||||
}
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
@ -176,6 +208,7 @@ namespace ProjectContainerShip
|
||||
}
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text);
|
||||
RefreshListBoxItems();
|
||||
}
|
||||
|
||||
@ -208,12 +241,22 @@ namespace ProjectContainerShip
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
|
||||
try
|
||||
{
|
||||
return;
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RefreshListBoxItems();
|
||||
_logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString());
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RefreshListBoxItems();
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -241,11 +284,13 @@ namespace ProjectContainerShip
|
||||
case "Хранилище":
|
||||
_company = new ShipSharingService(pictureBox.Width, pictureBox.Height, collection);
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
panelCompanyTools.Enabled = true;
|
||||
RefreshListBoxItems();
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Сохранение"
|
||||
@ -256,13 +301,16 @@ namespace ProjectContainerShip
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -276,14 +324,17 @@ namespace ProjectContainerShip
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
RefreshListBoxItems();
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -145,9 +145,9 @@ public partial class FormShipConfig : Form
|
||||
|
||||
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
if (_ship?.EntityShip is EntityContainerShip _catamaran)
|
||||
if (_ship?.EntityShip is EntityContainerShip _containerShip)
|
||||
{
|
||||
_catamaran.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
|
||||
_containerShip.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
|
||||
}
|
||||
DrawObject();
|
||||
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectContainerShip
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +16,27 @@ namespace ProjectContainerShip
|
||||
// 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)
|
||||
{
|
||||
string[] path = Directory.GetCurrentDirectory().Split('\\');
|
||||
string pathNeed = "";
|
||||
for (int i = 0; i < path.Length - 3; i++)
|
||||
{
|
||||
pathNeed += path[i] + "\\";
|
||||
}
|
||||
|
||||
services.AddSingleton<FormShipCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
|
||||
AddJsonFile($"{pathNeed}appSetting.json").Build()).CreateLogger());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,16 @@
|
||||
<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="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@ -23,4 +33,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appSetting.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
15
ProjectContainerShip/ProjectContainerShip/appSetting.json
Normal file
15
ProjectContainerShip/ProjectContainerShip/appSetting.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": { "path": "log.log" }
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Applicatoin": "Sample"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user
Требовалось заменить класс Exception на его более подходящих наследников