Compare commits

..

No commits in common. "ea555cc89719b619e6234fee39543348883c3344" and "d83972988a3f0d9162e839322172e9f5bc91b96f" have entirely different histories.

14 changed files with 198 additions and 237 deletions

View File

@ -1,4 +1,5 @@
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using System;
namespace HoistingCrane.CollectionGenericObjects namespace HoistingCrane.CollectionGenericObjects
{ {
public abstract class AbstractCompany public abstract class AbstractCompany
@ -30,7 +31,7 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
get get
{ {
return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-2; return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-3;
} }
} }
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> array) public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> array)
@ -40,6 +41,7 @@ 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,4 +1,5 @@
namespace HoistingCrane.CollectionGenericObjects using System;
namespace HoistingCrane.CollectionGenericObjects
{ {
public enum CollectionType public enum CollectionType
{ {

View File

@ -1,5 +1,6 @@
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using HoistingCrane.Exceptions; using System;
using System.Collections.Specialized;
namespace HoistingCrane.CollectionGenericObjects namespace HoistingCrane.CollectionGenericObjects
{ {
@ -35,14 +36,10 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
if (arr?.Get(i) != null) if (arr?.Get(i) != null)
{ {
try arr?.Get(i)?.SetPictureSize(pictureWidth, pictureHeight);
{ 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)
currentPosWidth--; currentPosWidth--;
else else
@ -54,6 +51,7 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
break; break;
} }
} }
} }
} }

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using HoistingCrane.Exceptions; using System;
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
@ -78,11 +79,11 @@ namespace HoistingCrane.CollectionGenericObjects
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename) public bool SaveData(string filename)
{ {
if (dict.Count == 0) if (dict.Count == 0)
{ {
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения"); return false;
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -93,7 +94,6 @@ 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,6 +104,7 @@ 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);
@ -122,30 +123,33 @@ namespace HoistingCrane.CollectionGenericObjects
} }
writer.Write(sb); writer.Write(sb);
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по грузовикам в хранилище из файла // /// Загрузка информации по грузовикам в хранилище из файла
/// </summary> // /// </summary>
/// <param name="filename"></param> // /// <param name="filename">Путь и имя файла</param>
/// <exception cref="Exception"></exception> // /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename) public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new FileNotFoundException("Файл не существует"); return false;
} }
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)
{ {
throw new InvalidOperationException("В файле не присутствуют данные"); return false;
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
throw new FormatException("В файле неверные данные"); return false;
} }
dict.Clear(); dict.Clear();
string strs = ""; string strs = "";
@ -160,29 +164,23 @@ namespace HoistingCrane.CollectionGenericObjects
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); return false;
} }
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 crane) if (elem?.CreateDrawningTrackedVehicle() is T truck)
{ {
try if (collection.Insert(truck) == -1)
{ {
if (collection.Insert(crane) == -1) return false;
{
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

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

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

@ -1,13 +0,0 @@
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,7 +1,15 @@
using HoistingCrane.CollectionGenericObjects; using HoistingCrane.CollectionGenericObjects;
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using HoistingCrane.Exceptions; using System;
using Microsoft.Extensions.Logging; using System.Collections.Generic;
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
@ -9,54 +17,80 @@ namespace HoistingCrane
private AbstractCompany? _company; private AbstractCompany? _company;
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection; private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
/// <summary> public FormCarCollection()
/// Логгер
/// </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(SetCrane); form.AddEvent(SetCar);
} }
private void SetCrane(DrawningTrackedVehicle drawningTrackedVehicle) private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle)
{ {
if (_company == null || drawningTrackedVehicle == null) return; if (_company == null || drawningTrackedVehicle == null)
try
{ {
if (_company + drawningTrackedVehicle != -1) return;
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
logger.LogInformation("Добавлен объект {nameObject}", drawningTrackedVehicle.GetType().Name);
}
else
{
MessageBox.Show("Не удалось добавить объект");
logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", drawningTrackedVehicle.GetType().Name);
}
} }
catch (CollectionOverflowException ex)
if (_company + drawningTrackedVehicle != -1)
{ {
MessageBox.Show("Ошибка переполнения коллекции"); MessageBox.Show("Объект добавлен");
logger.LogError("Ошибка: {Message}", ex.Message); 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;
@ -65,30 +99,15 @@ namespace HoistingCrane
{ {
return; return;
} }
try int pos = Convert.ToInt32(maskedTextBox.Text);
if ((_company - pos) != null)
{ {
int pos = Convert.ToInt32(maskedTextBox.Text); MessageBox.Show("Объект удален!");
if ((_company - pos) != null) pictureBox.Image = _company.Show();
{
MessageBox.Show("Объект удален!");
pictureBox.Image = _company.Show();
logger.LogInformation("Удаление авто по индексу {pos}", pos);
}
else
{
MessageBox.Show("Не удалось удалить объект");
logger.LogInformation("Не удалось удалить авто из коллекции по индексу {pos}", pos);
}
} }
catch (ObjectNotFoundException ex) else
{ {
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)
@ -134,22 +153,22 @@ namespace HoistingCrane
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка",
logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); MessageBoxButtons.OK, MessageBoxIcon.Error);
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,collectionType);RerfreshListBoxItems(); _storageCollection.AddCollection(textBoxCollectionName.Text,
collectionType);
RerfreshListBoxItems();
} }
private void buttonDeleteCollection_Click(object sender, EventArgs e) private void buttonDeleteCollection_Click(object sender, EventArgs e)
{ {
@ -160,28 +179,22 @@ 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("Коллекция не выбрана");
return; return;
} }
ICollectionGenericObjects<DrawningTrackedVehicle>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; ICollectionGenericObjects<DrawningTrackedVehicle>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
}; }
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
@ -201,16 +214,13 @@ namespace HoistingCrane
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
try if (_storageCollection.SaveData(saveFileDialog.FileName))
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
catch (Exception ex) else
{ {
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -224,17 +234,14 @@ namespace HoistingCrane
{ {
if(openFileDialog.ShowDialog() == DialogResult.OK) if(openFileDialog.ShowDialog() == DialogResult.OK)
{ {
try if (_storageCollection.LoadData(openFileDialog.FileName))
{ {
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
logger.LogInformation("Загрузка в файл: {filename}", saveFileDialog.FileName); RerfreshListBoxItems();
} }
catch(Exception ex) else
{ {
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не сохранилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -31,7 +31,6 @@ 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,15 +12,6 @@
<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,29 +1,18 @@
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();
ServiceCollection services = new(); Application.Run(new FormCarCollection());
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();
});
} }
} }
} }