Compare commits

..

No commits in common. "915c8cea9c11d702f03818c298767b2ce4e1c065" and "b54825c276b8fec131f853b904d63b823eccff95" have entirely different histories.

16 changed files with 145 additions and 259 deletions

View File

@ -48,14 +48,10 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawingPlane? obj = _collection?.Get(i); DrawingPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (Exception) { }
}
return bitmap; return bitmap;
} }

View File

@ -1,6 +1,4 @@
using ProjectSeaplane.Exceptions; namespace ProjectSeaplane.CollectionGenericObjects;
namespace ProjectSeaplane.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@ -35,26 +33,26 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) return null;
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count == _maxCount) throw new CollectionOverflowException(Count); if (Count == _maxCount) return -1;
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count == _maxCount) throw new CollectionOverflowException(Count); if (Count == _maxCount) return -1;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) return -1;
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) return null;
T obj = _collection[position]; T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;

View File

@ -1,6 +1,4 @@
using ProjectSeaplane.Exceptions; namespace ProjectSeaplane.CollectionGenericObjects;
namespace ProjectSeaplane.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@ -40,8 +38,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Length || position < 0) return null;
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
@ -57,11 +54,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
++index; ++index;
} }
throw new CollectionOverflowException(Count); return -1;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Length || position < 0)
return -1;
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@ -87,12 +85,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
--index; --index;
} }
throw new CollectionOverflowException(Count); return -1;
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Length || position < 0)
if (_collection[position] == null) throw new ObjectNotFoundException(position); return null;
T obj = _collection[position]; T obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return obj;

View File

@ -32,12 +32,11 @@ internal class PlaneSharingService : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
try if (_collection.Get(i) != null)
{ {
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(_placeSizeWidth * curWidth, curHeight * _placeSizeHeight + 4); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth, curHeight * _placeSizeHeight + 4);
} }
catch (Exception) { }
if (curWidth > 0) if (curWidth > 0)
curWidth--; curWidth--;
else else

View File

@ -1,5 +1,4 @@
using ProjectSeaplane.Drawings; using ProjectSeaplane.Drawings;
using ProjectSeaplane.Exceptions;
using System.Text; using System.Text;
namespace ProjectSeaplane.CollectionGenericObjects; namespace ProjectSeaplane.CollectionGenericObjects;
@ -79,11 +78,11 @@ public class StorageCollection<T>
/// </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 (_storages.Count == 0) if (_storages.Count == 0)
{ {
throw new Exception("В хранилище отсутствуют коллекции для сохранения"); return false;
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -120,6 +119,8 @@ public class StorageCollection<T>
} }
} }
return true;
} }
/// <summary> /// <summary>
@ -127,22 +128,22 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename) public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не существует"); 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 Exception("В файле нет данных"); return false;
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
throw new Exception("В файле неверные данные"); return false;
} }
_storages.Clear(); _storages.Clear();
string strs = ""; string strs = "";
@ -157,29 +158,23 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
throw new Exception("Не удалось создать коллекцию"); 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?.CreateDrawningPlane() is T plane) if (elem?.CreateDrawningPlane() is T ship)
{ {
try if (collection.Insert(ship) == -1)
{ {
if (collection.Insert(plane) == -1) return false;
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true;
} }
} }

View File

@ -49,9 +49,9 @@ public class DrawingPlane
_drawingPlaneHeight = drawingSeaplaneHeight; _drawingPlaneHeight = drawingSeaplaneHeight;
} }
public DrawingPlane(EntityPlane plane) : this() public DrawingPlane(EntityPlane ship) : this()
{ {
EntityPlane = new EntityPlane(plane.Speed, plane.Weight, plane.BodyColor); EntityPlane = new EntityPlane(ship.Speed, ship.Weight, ship.BodyColor);
} }
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)

View File

@ -14,9 +14,9 @@ public class DrawingSeaplane : DrawingPlane
EntityPlane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, floats, inflatableBoat); EntityPlane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, floats, inflatableBoat);
} }
public DrawingSeaplane(EntitySeaplane plane) : base(190, 85) public DrawingSeaplane(EntitySeaplane ship) : base(190, 85)
{ {
EntityPlane = new EntitySeaplane(plane.Speed, plane.Weight, plane.BodyColor, plane.AdditionalColor, plane.Floats, plane.InflatableBoat); EntityPlane = new EntitySeaplane(ship.Speed, ship.Weight, ship.BodyColor, ship.AdditionalColor, ship.Floats, ship.InflatableBoat);
} }
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)

View File

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Exceptions;
[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) { }
}

View File

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Exceptions;
[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) { }
}

View File

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Exceptions;
[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) { }
}

View File

@ -66,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(677, 24); groupBoxTools.Location = new Point(764, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 583); groupBoxTools.Size = new Size(200, 603);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -98,7 +98,7 @@
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(3, 50); maskedTextBoxPosition.Location = new Point(3, 97);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(182, 23); maskedTextBoxPosition.Size = new Size(182, 23);
@ -107,7 +107,7 @@
// //
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Location = new Point(3, 197); buttonRefresh.Location = new Point(3, 216);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(182, 41); buttonRefresh.Size = new Size(182, 41);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@ -117,7 +117,7 @@
// //
// buttonDelPlane // buttonDelPlane
// //
buttonDelPlane.Location = new Point(3, 107); buttonDelPlane.Location = new Point(3, 126);
buttonDelPlane.Name = "buttonDelPlane"; buttonDelPlane.Name = "buttonDelPlane";
buttonDelPlane.Size = new Size(182, 41); buttonDelPlane.Size = new Size(182, 41);
buttonDelPlane.TabIndex = 4; buttonDelPlane.TabIndex = 4;
@ -127,7 +127,7 @@
// //
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Location = new Point(3, 154); buttonGoToCheck.Location = new Point(3, 173);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(182, 41); buttonGoToCheck.Size = new Size(182, 41);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@ -244,7 +244,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(677, 583); pictureBox.Size = new Size(764, 603);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -253,7 +253,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(877, 24); menuStrip.Size = new Size(964, 24);
menuStrip.TabIndex = 2; menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1"; menuStrip.Text = "menuStrip1";
// //
@ -292,7 +292,7 @@
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(877, 607); ClientSize = new Size(964, 627);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);

View File

@ -1,7 +1,5 @@
using Microsoft.Extensions.Logging; using ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.Drawings; using ProjectSeaplane.Drawings;
using ProjectSeaplane.Exceptions;
using System.Windows.Forms; using System.Windows.Forms;
namespace ProjectSeaplane; namespace ProjectSeaplane;
@ -12,14 +10,10 @@ public partial class FormSeaplaneCollection : Form
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
private readonly ILogger _logger; public FormSeaplaneCollection()
public FormSeaplaneCollection(ILogger<FormSeaplaneCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
@ -35,8 +29,6 @@ public partial class FormSeaplaneCollection : Form
} }
private void SetPlane(DrawingPlane? plane) private void SetPlane(DrawingPlane? plane)
{
try
{ {
if (_company == null || plane == null) if (_company == null || plane == null)
{ {
@ -46,17 +38,59 @@ public partial class FormSeaplaneCollection : Form
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + plane.GetDataForSave());
} }
} else
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawingPlane drawningPlane;
switch (type)
{
case nameof(DrawingPlane):
drawningPlane = new DrawingPlane(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawingSeaplane):
drawningPlane = new DrawingSeaplane(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningPlane != -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 buttonDelPlane_Click(object sender, EventArgs e) private void buttonDelPlane_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
@ -70,19 +104,14 @@ public partial class FormSeaplaneCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
} }
} else
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -95,8 +124,6 @@ public partial class FormSeaplaneCollection : Form
DrawingPlane? plane = null; DrawingPlane? plane = null;
int counter = 100; int counter = 100;
try
{
while (plane == null) while (plane == null)
{ {
plane = _company.GetRandomObject(); plane = _company.GetRandomObject();
@ -106,17 +133,18 @@ public partial class FormSeaplaneCollection : Form
break; break;
} }
} }
if (plane == null)
{
return;
}
FormSeaplane form = new() FormSeaplane form = new()
{ {
SetPlane = plane SetPlane = plane
}; };
form.ShowDialog(); form.ShowDialog();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonRefresh_Click(object sender, EventArgs e) private void buttonRefresh_Click(object sender, EventArgs e)
{ {
@ -136,8 +164,6 @@ public partial class FormSeaplaneCollection : Form
return; return;
} }
try
{
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@ -147,14 +173,9 @@ public partial class FormSeaplaneCollection : Form
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
private void buttonCollectionDel_Click(object sender, EventArgs e) private void buttonCollectionDel_Click(object sender, EventArgs e)
@ -164,20 +185,12 @@ public partial class FormSeaplaneCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
private void RerfreshListBoxItems() private void RerfreshListBoxItems()
@ -191,6 +204,7 @@ public partial class FormSeaplaneCollection : Form
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
} }
} }
} }
private void buttonCreateCompany_Click(object sender, EventArgs e) private void buttonCreateCompany_Click(object sender, EventArgs e)
@ -223,16 +237,15 @@ public partial class FormSeaplaneCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
try if (_storageCollection.SaveData(saveFileDialog.FileName))
{ {
_storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно",
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
catch (Exception ex) else
{ {
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не сохранилось", "Результат",
_logger.LogError("Ошибка: {Message}", ex.Message); MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@ -241,17 +254,16 @@ public partial class FormSeaplaneCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
try if (_storageCollection.LoadData(openFileDialog.FileName))
{ {
_storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно",
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
catch (Exception ex) else
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не загрузилось", "Результат",
_logger.LogError("Ошибка: {Message}", ex.Message); MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -126,7 +126,4 @@
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>255, 17</value> <value>255, 17</value>
</metadata> </metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root> </root>

View File

@ -1,8 +1,3 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
namespace ProjectSeaplane namespace ProjectSeaplane
{ {
internal static class Program internal static class Program
@ -16,31 +11,7 @@ namespace ProjectSeaplane
// 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(); ApplicationConfiguration.Initialize();
Application.Run(new FormSeaplaneCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormSeaplaneCollection>());
}
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<FormSeaplaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
} }
} }
} }

View File

@ -8,17 +8,6 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<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,15 +0,0 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}