Compare commits

...

7 Commits

14 changed files with 224 additions and 185 deletions

View File

@ -1,5 +1,4 @@
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using System;
namespace HoistingCrane.CollectionGenericObjects namespace HoistingCrane.CollectionGenericObjects
{ {
public abstract class AbstractCompany public abstract class AbstractCompany
@ -31,7 +30,7 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
get get
{ {
return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-3; return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-2;
} }
} }
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> array) public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> array)
@ -41,7 +40,6 @@ namespace HoistingCrane.CollectionGenericObjects
arr = array; arr = array;
arr.MaxCount = GetMaxCount; arr.MaxCount = GetMaxCount;
} }
public static int operator +(AbstractCompany company, DrawningTrackedVehicle car) public static int operator +(AbstractCompany company, DrawningTrackedVehicle car)
{ {
return company.arr?.Insert(car) ?? -1; return company.arr?.Insert(car) ?? -1;

View File

@ -1,5 +1,4 @@
using System; namespace HoistingCrane.CollectionGenericObjects
namespace HoistingCrane.CollectionGenericObjects
{ {
public enum CollectionType public enum CollectionType
{ {

View File

@ -1,6 +1,5 @@
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using System; using HoistingCrane.Exceptions;
using System.Collections.Specialized;
namespace HoistingCrane.CollectionGenericObjects namespace HoistingCrane.CollectionGenericObjects
{ {
@ -36,8 +35,12 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
if (arr?.Get(i) != null) if (arr?.Get(i) != null)
{ {
arr?.Get(i)?.SetPictureSize(pictureWidth, pictureHeight); try
arr?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15); {
arr?.Get(i)?.SetPictureSize(pictureWidth, pictureHeight);
arr?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15);
}
catch (ObjectNotFoundException) { }
} }
if (currentPosWidth > 0) if (currentPosWidth > 0)
@ -51,7 +54,6 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
break; break;
} }
} }
} }
} }

View File

@ -1,5 +1,4 @@
using System; namespace HoistingCrane.CollectionGenericObjects
namespace HoistingCrane.CollectionGenericObjects
{ {
public interface ICollectionGenericObjects<T> public interface ICollectionGenericObjects<T>
where T: class where T: class

View File

@ -1,6 +1,4 @@
using System; using HoistingCrane.Exceptions;
using System.CodeDom.Compiler;
namespace HoistingCrane.CollectionGenericObjects namespace HoistingCrane.CollectionGenericObjects
{ {
public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : class public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : class
@ -44,19 +42,15 @@ namespace HoistingCrane.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= Count || position < 0) return null;
return list[position]; return list[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (Count == _maxCount) if (Count == _maxCount)
{ {
return -1; throw new CollectionOverflowException(Count);
} }
list.Add(obj); list.Add(obj);
return Count; return Count;
@ -64,27 +58,18 @@ namespace HoistingCrane.CollectionGenericObjects
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO проверка, что не превышено максимальное количество элементов if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
// TODO проверка позиции if (Count == _maxCount) throw new CollectionOverflowException(Count);
// TODO вставка по позиции
if (position < 0 || position >= Count || Count == _maxCount)
{
return -1;
}
list.Insert(position, obj); list.Insert(position, obj);
return position; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
// TODO проверка позиции if (position < 0 || position >= list.Count) throw new PositionOutOfCollectionException(position);
// TODO удаление объекта из списка T? temp = list[position];
if (position >= 0 && position < list.Count) list.RemoveAt(position);
{ return temp;
T? temp = list[position];
list.RemoveAt(position);
return temp;
}
return null;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,5 +1,4 @@
using System; using HoistingCrane.Exceptions;
namespace HoistingCrane.CollectionGenericObjects namespace HoistingCrane.CollectionGenericObjects
{ {
public class MassivGenericObjects<T> : ICollectionGenericObjects<T> where T : class public class MassivGenericObjects<T> : ICollectionGenericObjects<T> where T : class
@ -39,62 +38,64 @@ namespace HoistingCrane.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < arr.Length) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
{ return arr[position];
return arr[position];
}
return null;
}
public IEnumerable<T?> GetItems()
{
for(int i = 0; i < arr.Length; i++)
{
yield return arr[i];
}
} }
public int Insert(T obj) public int Insert(T obj)
{ {
int countObjectNotNull = 0;
for(int i = 0; i < Count; i++)
{
if (arr[i] != null) countObjectNotNull += 1;
}
if(countObjectNotNull == MaxCount) throw new CollectionOverflowException(Count);
return Insert(obj, 0); return Insert(obj, 0);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
//todo Проверка позиции if (position < 0 || position >= Count)
if (position < 0 || position > Count)
{ {
return -1; throw new PositionOutOfCollectionException(position);
} }
int copyPos = position - 1;
if (arr[position] == null) while (position < Count)
{ {
arr[position] = obj; if (arr[position] == null)
return position;
}
else
{
if (Insert(obj, position + 1) != -1)
{
return position;
}
if (Insert(obj, position - 1) != -1)
{ {
arr[position] = obj;
return position; return position;
} }
position++;
} }
return -1; while (copyPos > 0)
{
if (arr[copyPos] == null)
{
arr[copyPos] = obj;
return copyPos;
}
copyPos--;
}
throw new CollectionOverflowException(Count);
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= 0 && position < Count) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (arr[position] == null) throw new ObjectNotFoundException(position);
T? temp = arr[position];
arr[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < arr.Length; i++)
{ {
T? temp = arr[position]; yield return arr[i];
arr[position] = null;
return temp;
} }
return null;
} }
} }
} }

View File

@ -1,7 +1,6 @@
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using System; using HoistingCrane.Exceptions;
using System.Text; using System.Text;
namespace HoistingCrane.CollectionGenericObjects namespace HoistingCrane.CollectionGenericObjects
{ {
public class StorageCollection<T> where T : DrawningTrackedVehicle public class StorageCollection<T> where T : DrawningTrackedVehicle
@ -79,11 +78,11 @@ namespace HoistingCrane.CollectionGenericObjects
/// </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 (dict.Count == 0) if (dict.Count == 0)
{ {
return false; throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -94,6 +93,7 @@ namespace HoistingCrane.CollectionGenericObjects
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in dict) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in dict)
{ {
StringBuilder sb = new(); StringBuilder sb = new();
@ -104,7 +104,6 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
continue; continue;
} }
sb.Append(value.Key); sb.Append(value.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType); sb.Append(value.Value.GetCollectionType);
@ -123,33 +122,30 @@ namespace HoistingCrane.CollectionGenericObjects
} }
writer.Write(sb); writer.Write(sb);
} }
} }
return true;
} }
/// <summary> /// <summary>
// /// Загрузка информации по грузовикам в хранилище из файла /// Загрузка информации по грузовикам в хранилище из файла
// /// </summary> /// </summary>
// /// <param name="filename">Путь и имя файла</param> /// <param name="filename"></param>
// /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <exception cref="Exception"></exception>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует");
} }
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 InvalidOperationException("В файле не присутствуют данные");
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
return false; throw new FormatException("В файле неверные данные");
} }
dict.Clear(); dict.Clear();
string strs = ""; string strs = "";
@ -164,23 +160,29 @@ namespace HoistingCrane.CollectionGenericObjects
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningTrackedVehicle() is T truck) if (elem?.CreateDrawningTrackedVehicle() is T crane)
{ {
if (collection.Insert(truck) == -1) try
{ {
return false; if (collection.Insert(crane) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch(CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
} }
} }
} }
dict.Add(record[0], collection); dict.Add(record[0], collection);
} }
return true;
} }
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace HoistingCrane.Exceptions
{
[Serializable]
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: count" + count) { }
public CollectionOverflowException() : base(){ }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace HoistingCrane.Exceptions
{
[Serializable]
public 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 context) : base(info, context) { }
}
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace HoistingCrane.Exceptions
{
[Serializable]
public 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 context) : base(info, context){ }
}
}

View File

@ -1,15 +1,7 @@
using HoistingCrane.CollectionGenericObjects; using HoistingCrane.CollectionGenericObjects;
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using System; using HoistingCrane.Exceptions;
using System.Collections.Generic; using Microsoft.Extensions.Logging;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HoistingCrane namespace HoistingCrane
{ {
public partial class FormCarCollection : Form public partial class FormCarCollection : Form
@ -17,80 +9,54 @@ namespace HoistingCrane
private AbstractCompany? _company; private AbstractCompany? _company;
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection; private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
public FormCarCollection() /// <summary>
/// Логгер
/// </summary>
private readonly ILogger logger;
public FormCarCollection(ILogger<FormCarCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
panelCompanyTool.Enabled = false; panelCompanyTool.Enabled = false;
this.logger = logger;
} }
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{ {
panelCompanyTool.Enabled = false; panelCompanyTool.Enabled = false;
} }
private void CreateObject(string type)
{
DrawningTrackedVehicle drawning;
if (_company == null) return;
Random rand = new();
switch (type)
{
case nameof(DrawningHoistingCrane):
drawning = new DrawningHoistingCrane(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand), GetColor(rand), true, true);
break;
case nameof(DrawningTrackedVehicle):
drawning = new DrawningTrackedVehicle(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand));
break;
default:
return;
}
if ((_company + drawning) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
private void buttonCreateHoistingCrane_Click(object sender, EventArgs e) private void buttonCreateHoistingCrane_Click(object sender, EventArgs e)
{ {
FormCarConfig form = new(); FormCarConfig form = new();
form.Show(); form.Show();
form.AddEvent(SetCar); form.AddEvent(SetCrane);
} }
private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle) private void SetCrane(DrawningTrackedVehicle drawningTrackedVehicle)
{ {
if (_company == null || drawningTrackedVehicle == null) if (_company == null || drawningTrackedVehicle == null) return;
try
{ {
return; if (_company + drawningTrackedVehicle != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
logger.LogInformation("Добавлен объект {nameObject}", drawningTrackedVehicle.GetType().Name);
}
else
{
MessageBox.Show("Не удалось добавить объект");
logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", drawningTrackedVehicle.GetType().Name);
}
}
catch (CollectionOverflowException ex)
{
MessageBox.Show("Ошибка переполнения коллекции");
logger.LogError("Ошибка: {Message}", ex.Message);
} }
if (_company + drawningTrackedVehicle != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
} }
private void buttonDeleteCar_Click(object sender, EventArgs e) private void buttonDeleteCar_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{ {
return; return;
@ -99,15 +65,30 @@ namespace HoistingCrane
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); try
if ((_company - pos) != null)
{ {
MessageBox.Show("Объект удален!"); int pos = Convert.ToInt32(maskedTextBox.Text);
pictureBox.Image = _company.Show(); if ((_company - pos) != null)
{
MessageBox.Show("Объект удален!");
pictureBox.Image = _company.Show();
logger.LogInformation("Удаление авто по индексу {pos}", pos);
}
else
{
MessageBox.Show("Не удалось удалить объект");
logger.LogInformation("Не удалось удалить авто из коллекции по индексу {pos}", pos);
}
} }
else catch (ObjectNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Ошибка: отсутствует объект");
logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Ошибка: неправильная позиция");
logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
private void buttonRefresh_Click(object sender, EventArgs e) private void buttonRefresh_Click(object sender, EventArgs e)
@ -153,22 +134,22 @@ namespace HoistingCrane
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return; return;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
collectionType = CollectionType.Massive; collectionType = CollectionType.Massive;
logger.LogInformation("Создана коллекция '{nameCol}' , название: {name}", collectionType, textBoxCollectionName.Text);
} }
else if (radioButtonList.Checked) else if (radioButtonList.Checked)
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
logger.LogInformation("Создана коллекция '{nameCol}' , название: {name}", collectionType, textBoxCollectionName.Text);
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, _storageCollection.AddCollection(textBoxCollectionName.Text,collectionType);RerfreshListBoxItems();
collectionType);
RerfreshListBoxItems();
} }
private void buttonDeleteCollection_Click(object sender, EventArgs e) private void buttonDeleteCollection_Click(object sender, EventArgs e)
{ {
@ -179,11 +160,17 @@ namespace HoistingCrane
} }
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
return; return;
if (listBoxCollection.SelectedItem != null)
{
logger.LogInformation("Коллекция '{name}' успешно удалена", listBoxCollection.SelectedItem.ToString());
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void buttonCreateCompany_Click(object sender, EventArgs e) private void buttonCreateCompany_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
@ -194,7 +181,7 @@ namespace HoistingCrane
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} };
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
@ -214,13 +201,16 @@ namespace HoistingCrane
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); 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);
} }
} }
} }
@ -234,14 +224,17 @@ namespace HoistingCrane
{ {
if(openFileDialog.ShowDialog() == DialogResult.OK) if(openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems(); RerfreshListBoxItems();
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);
} }
} }
} }

View File

@ -31,6 +31,7 @@ namespace HoistingCrane
panelColorPurple.MouseDown += panel_MouseDown; panelColorPurple.MouseDown += panel_MouseDown;
buttonCancel.Click += (sender, e) => Close(); buttonCancel.Click += (sender, e) => Close();
} }
/// <summary> /// <summary>
/// Привязка метода к событию /// Привязка метода к событию
/// </summary> /// </summary>

View File

@ -12,6 +12,15 @@
<None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" /> <None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.9" />
<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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -1,18 +1,29 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
namespace HoistingCrane namespace HoistingCrane
{ {
internal static class Program internal static class Program
{ {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormCarCollection()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormCarCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
// Èíèöèàëèçèðóåì Serilog
Log.Logger = new LoggerConfiguration().WriteTo.File("E:\\myLog.log").CreateLogger();
services.AddSingleton<FormCarCollection>().AddLogging(builder =>
{
builder.AddSerilog();
});
} }
} }
} }