This commit is contained in:
Inna Pruidze 2024-06-16 19:46:37 +04:00
parent 7f58bbb1ad
commit 5071187623
14 changed files with 241 additions and 292 deletions

View File

@ -17,8 +17,8 @@ public abstract class AbstractCompany
// Коллекция автомобилей // Коллекция автомобилей
protected ICollectionGenObj<DrawningBase>? _collection = null; protected ICollectionGenObj<DrawningBase>? _collection = null;
private int GetMaxCount => _pictureWidth * _pictureHeight / private int GetMaxCount => (_pictureWidth / (_placeSizeWidth + 20))
(_placeSizeWidth * _placeSizeHeight); * ( _pictureHeight / (_placeSizeHeight + 4));
public AbstractCompany(int picWidth, int picHeight, public AbstractCompany(int picWidth, int picHeight,
ICollectionGenObj<DrawningBase>? collection) ICollectionGenObj<DrawningBase>? collection)
@ -51,20 +51,22 @@ public abstract class AbstractCompany
Bitmap bitmap = new(_pictureWidth, _pictureHeight); Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap); Graphics graphics = Graphics.FromImage(bitmap);
DrawBackground(graphics); DrawBackground(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) SetObjectsPosition(_collection.Count - 1);
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
DrawningBase? obj = _collection?.GetItem(i); DrawningBase? obj = _collection?.GetItem(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
return bitmap; return bitmap;
} }
// Вывод заднего фона // Вывод заднего фона
protected abstract void DrawBackground(Graphics g); protected abstract void DrawBackground(Graphics g);
// Расстановка объектов // Расстановка объектов
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition(int border);
} }

View File

@ -1,5 +1,4 @@
 using ProjectCruiser.Exceptions;
using ProjectCruiser.Exceptions;
namespace ProjectCruiser.CollectionGenericObj; namespace ProjectCruiser.CollectionGenericObj;
@ -11,7 +10,7 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
// Максимально допустимое число объектов в массиве // Максимально допустимое число объектов в массиве
private int _maxCount; private int _maxCount;
public int Count => _collection.Count(s => s != null); public int Count => _collection.Count(s => (s != null));
public int MaxCount public int MaxCount
{ {
@ -20,10 +19,10 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
{ {
if (value > 0) if (value > 0)
{ {
_maxCount = value;
if (_collection.Length == 0) _collection = new T?[value]; if (_collection.Length == 0) _collection = new T?[value];
else Array.Resize(ref _collection, value); else Array.Resize(ref _collection, value);
_maxCount = value;
} }
} }
} }
@ -38,9 +37,7 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
// methods : // methods :
public T? GetItem(int index) public T? GetItem(int index)
{ {
try if (index > _maxCount)
{
if (index > Count)
throw new CollectionOverflowException(index); throw new CollectionOverflowException(index);
if (index < 0) if (index < 0)
throw new PositionOutOfCollectionException(index); throw new PositionOutOfCollectionException(index);
@ -49,37 +46,22 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
throw new ObjectNotFoundException(index); throw new ObjectNotFoundException(index);
return _collection[index]; return _collection[index];
}
catch (CollectionOverflowException ex) // CollectionOverflowException
{ // PositionOutOfCollectionException
Console.WriteLine(ex.Message); // ObjectNotFoundException
return null;
}
catch (ObjectNotFoundException ex)
{
Console.WriteLine(ex.Message);
return null;
}
catch (PositionOutOfCollectionException ex)
{
Console.WriteLine(ex.Message);
return null;
}
} }
public int Insert(T? item) public int Insert(T? item)
{ {
if (item == null) { return -1; } if (item == null) throw
new NullReferenceException("> Inserting item is null");
try // выход за границы, курируется CollectionOverflowException // выход за границы, курируется CollectionOverflowException
{ if (Count >= _maxCount) throw new CollectionOverflowException(Count);
if (Count >= _maxCount)
{
throw new CollectionOverflowException(Count);
}
// any empty place -> fill immediately // any empty place -> fill immediately
for (int i = 0; i < _collection.Length; i++) for (int i = Count; i < _maxCount; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@ -88,22 +70,18 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
} }
} }
return Count; return Count;
}
catch (CollectionOverflowException ex) // NullReferenceException
{ // CollectionOverflowException
Console.WriteLine(ex.Message);
return -1;
}
} }
public int Insert(T? item, int index) public int Insert(T? item, int index)
{
try
{ {
if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index);
if (Count >= _maxCount) throw new CollectionOverflowException(Count); if (Count >= _maxCount) throw new CollectionOverflowException(Count);
if (item == null) throw new ObjectNotFoundException(index); if (item == null) throw
new NullReferenceException("> Inserting item (at position) is null");
if (_collection[index] == null) if (_collection[index] == null)
{ {
@ -126,33 +104,18 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
_collection[firstNullIndex] = item; _collection[firstNullIndex] = item;
return firstNullIndex; return firstNullIndex;
} }
}
catch (CollectionOverflowException ex) // PositionOutOfCollectionException
{ // CollectionOverflowException
Console.WriteLine(ex.Message); // NullReferenceException
return -1;
}
catch (ObjectNotFoundException ex)
{
Console.WriteLine(ex.Message);
return -1;
}
catch (PositionOutOfCollectionException ex)
{
Console.WriteLine(ex.Message);
return -1;
}
} }
public T? Remove(int index) public T? Remove(int index)
{
try
{ {
if (index >= _maxCount || index < 0) if (index >= _maxCount || index < 0)
// on the other positions items don't exist // on the other positions items don't exist
{ {
throw new CollectionOverflowException(index); throw new PositionOutOfCollectionException(index);
// [?] PositionOutOfCollectionException <<<
} }
T? item = _collection[index]; T? item = _collection[index];
@ -161,17 +124,9 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
if (item == null) throw new ObjectNotFoundException(index); if (item == null) throw new ObjectNotFoundException(index);
return item; return item;
}
catch (CollectionOverflowException ex) // PositionOutOfCollectionException
{ // ObjectNotFoundException
Console.WriteLine(ex.Message);
return null;
}
catch (ObjectNotFoundException ex)
{
Console.WriteLine(ex.Message);
return null;
}
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,8 +1,4 @@
using System; using ProjectCruiser.Exceptions;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using ProjectCruiser.Exceptions;
namespace ProjectCruiser.CollectionGenericObj; namespace ProjectCruiser.CollectionGenericObj;
@ -41,9 +37,7 @@ public class ListGenObj<T> : ICollectionGenObj<T>
public T? GetItem(int position) public T? GetItem(int position)
{ {
try if (position > _maxCount)
{
if (position > Count)
throw new CollectionOverflowException(position); throw new CollectionOverflowException(position);
if (position < 0) if (position < 0)
throw new PositionOutOfCollectionException(position); throw new PositionOutOfCollectionException(position);
@ -53,80 +47,38 @@ public class ListGenObj<T> : ICollectionGenObj<T>
return _collection[position]; return _collection[position];
} }
catch (CollectionOverflowException ex)
{
Console.WriteLine(ex.Message);
return null;
}
catch (ObjectNotFoundException ex)
{
Console.WriteLine(ex.Message);
return null;
}
catch (PositionOutOfCollectionException ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
public int Insert(T? obj) public int Insert(T? obj)
{ {
if (obj == null) { return -1; } if (obj == null)
throw new NullReferenceException("> Inserting object is null");
try // выход за границы, курируется CollectionOverflowException // выход за границы, курируется CollectionOverflowException
{ if (Count >= _maxCount) throw new CollectionOverflowException(Count);
if (Count >= _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
catch (CollectionOverflowException ex)
{
Console.WriteLine(ex.Message);
return -1;
}
}
public int Insert(T? obj, int position) public int Insert(T? obj, int position)
{ {
try if (position < 0 || position >= _maxCount)
{ throw new PositionOutOfCollectionException(position);
if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position);
if (Count >= _maxCount) throw new CollectionOverflowException(Count); if (Count >= _maxCount) throw new CollectionOverflowException(Count);
if (obj == null) throw new ObjectNotFoundException(position); if (obj == null)
throw new NullReferenceException("> Inserting object (at position) is null");
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
catch (CollectionOverflowException ex)
{
Console.WriteLine(ex.Message);
return -1;
}
catch (ObjectNotFoundException ex)
{
Console.WriteLine(ex.Message);
return -1;
}
catch (PositionOutOfCollectionException ex)
{
Console.WriteLine(ex.Message);
return -1;
}
}
public T? Remove(int position) public T? Remove(int position)
{ {
try {
if (position >= _maxCount || position < 0) if (position >= _maxCount || position < 0)
// on the other positions items don't exist // on the other positions items don't exist
{ {
throw new CollectionOverflowException(position); throw new PositionOutOfCollectionException(position);
} }
T? item = _collection[position]; T? item = _collection[position];
@ -136,17 +88,6 @@ public class ListGenObj<T> : ICollectionGenObj<T>
return item; return item;
} }
catch (CollectionOverflowException ex)
{
Console.WriteLine(ex.Message);
return null;
}
catch (ObjectNotFoundException ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
{ {

View File

@ -41,27 +41,33 @@ public class ShipSharingService : AbstractCompany
} }
} }
protected override void SetObjectsPosition() protected override void SetObjectsPosition(int border)
{ {
int index_collection = 0; int index_collection = 0;
int newX = fromBorder + 6, newY = fromCeiling + 6; int newY = fromCeiling + 4;
if (_collection != null) if (_collection != null)
{ {
for (int i = 0; i < MaxInColon; ++i) for (int i = 0; i < MaxInColon; i++)
{ {
newX = fromBorder + 2; int newX = fromBorder + 2;
for (int j = 0; j < MaxInRow; ++j) for (int j = 0; j < MaxInRow; j++)
{ {
if (_collection.GetItem(index_collection) != null) // TRY / CATCH [?]
{ _collection.GetItem(index_collection).SetPictureSize(
_collection.GetItem(index_collection).SetPictureSize(_pictureWidth, _pictureHeight); _pictureWidth, _pictureHeight);
_collection.GetItem(index_collection).SetPosition(newX, newY); _collection.GetItem(index_collection).SetPosition(newX, newY);
newX += _placeSizeWidth + between + 2; newX += _placeSizeWidth + between + 2;
if (index_collection < border)
{
index_collection++; index_collection++;
} }
else return;
} }
newY += _placeSizeHeight + 2; newY += _placeSizeHeight + 1;
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System.Text; using System.Security.Cryptography;
using System.Text;
using ProjectCruiser.DrawningSamples; using ProjectCruiser.DrawningSamples;
using ProjectCruiser.Exceptions; using ProjectCruiser.Exceptions;
@ -32,7 +33,7 @@ public class StorageCollection<T>
if (name == null || _storages.ContainsKey(name) if (name == null || _storages.ContainsKey(name)
|| collType == CollectionType.None) || collType == CollectionType.None)
{ {
return; throw new NullReferenceException("> Not enough information to save");
} }
ICollectionGenObj<T> collection = CreateCollection(collType); ICollectionGenObj<T> collection = CreateCollection(collType);
@ -43,7 +44,7 @@ public class StorageCollection<T>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (_storages.ContainsKey(name)) _storages.Remove(name); if (_storages.ContainsKey(name)) _storages.Remove(name);
return; else throw new NullReferenceException("> No such key in the list");
} }
// Доступ к коллекции ( по ключу-строке - её имени ) - индексатор [!!!] // Доступ к коллекции ( по ключу-строке - её имени ) - индексатор [!!!]
@ -111,7 +112,7 @@ public class StorageCollection<T>
// Загрузка информации по кораблям в хранилище из файла // Загрузка информации по кораблям в хранилище из файла
public void LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) throw new FileNotFoundException(); if (!File.Exists(filename)) throw new FileNotFoundException("> No such file");
string bufferTextFromFile = ""; string bufferTextFromFile = "";
@ -145,14 +146,13 @@ public class StorageCollection<T>
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) // > if (record.Length != 4) // >
// key | collType | maxcount | all next inf > 4 // key | collType | maxcount | all next inf > 4
{ { continue; }
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenObj<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenObj<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
throw new NullReferenceException("> Failed to create collection"); throw new NullReferenceException("[!] Failed to create collection");
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, string[] set = record[3].Split(_separatorItems,
@ -164,13 +164,15 @@ public class StorageCollection<T>
{ {
try try
{ {
if (collection.Insert(ship) == -1) collection.Insert(ship);
throw new IndexOutOfRangeException(
"> Failed to add to collection : " + record[3]); // throw new IndexOutOfRangeException IF IT WAS Insert(item, pos)
// NullReferenceException >
// CollectionOverflowException >
} }
catch (CollectionOverflowException e) catch (Exception e)
{ {
throw new CollectionOverflowException("Collection overflowed", e); throw new Exception(e.Message);
} }
} }
} }

View File

@ -6,7 +6,7 @@ namespace ProjectCruiser.Exceptions;
internal class CollectionOverflowException : ApplicationException internal class CollectionOverflowException : ApplicationException
{ {
public CollectionOverflowException(int count) public CollectionOverflowException(int count)
: base("Possible accsess of collection is over : " + count) { } : base("<> Possible accsess\nof collection is over : " + count) { }
public CollectionOverflowException() : base() { } public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { } public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : public CollectionOverflowException(string message, Exception exception) :

View File

@ -6,7 +6,7 @@ namespace ProjectCruiser.Exceptions;
internal class ObjectNotFoundException : ApplicationException internal class ObjectNotFoundException : ApplicationException
{ {
public ObjectNotFoundException(int i) public ObjectNotFoundException(int i)
: base("Didn't find obj on this position : " + i) { } : base("<> Didn't find obj\non this position : " + i) { }
public ObjectNotFoundException() : base() { } public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { } public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) public ObjectNotFoundException(string message, Exception exception)

View File

@ -6,7 +6,7 @@ namespace ProjectCruiser.Exceptions;
internal class PositionOutOfCollectionException : ApplicationException internal class PositionOutOfCollectionException : ApplicationException
{ {
public PositionOutOfCollectionException(int i) public PositionOutOfCollectionException(int i)
: base("Out of collection boarder. Position : " + i) { } : base("<> Out of collection\nboarder. Position : " + i) { }
public PositionOutOfCollectionException() : base() { } public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { } public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, public PositionOutOfCollectionException(string message,

View File

@ -1,5 +1,6 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog; using Serilog;
namespace ProjectCruiser namespace ProjectCruiser
@ -16,26 +17,28 @@ namespace ProjectCruiser
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
ServiceCollection services = new(); ServiceCollection services = new();
ConfigureServices(services); ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider(); using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<ServiceForm2>()); Application.Run(serviceProvider.GetRequiredService<ServiceForm2>());
}
/// Êîíôèãóðàöèÿ ñåðâèñà DI }
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services) 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<ServiceForm2>().AddLogging(option => services.AddSingleton<ServiceForm2>().AddLogging(option =>
{ {
option.SetMinimumLevel(LogLevel.Information); option.SetMinimumLevel(LogLevel.Information);
// [*] option.AddSerilog("serilog.config"); option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(
option.AddSerilog("serilog.config"); new ConfigurationBuilder().AddJsonFile(
$"{pathNeed}serilog.json").Build()).CreateLogger());
// instead of :
// option.SetMinimumLevel(LogLevel.Information);
// option.AddNLog("nlog.config");
}); });
} }
} }

View File

@ -9,13 +9,15 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <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="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" /> <PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
</ItemGroup> <PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<ItemGroup>
<None Update="serilog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -221,7 +221,7 @@
btnDelete.TabIndex = 4; btnDelete.TabIndex = 4;
btnDelete.Text = "Delete"; btnDelete.Text = "Delete";
btnDelete.UseVisualStyleBackColor = true; btnDelete.UseVisualStyleBackColor = true;
btnDelete.Click += btnRemoveCar_Click; btnDelete.Click += btnRemoveShip_Click;
// //
// btnAddCruiser // btnAddCruiser
// //

View File

@ -1,7 +1,7 @@
using ProjectCruiser.CollectionGenericObj; using ProjectCruiser.CollectionGenericObj;
using ProjectCruiser.DrawningSamples; using ProjectCruiser.DrawningSamples;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using ProjectCruiser.Exceptions;
// using NLog.Extensions.Logging; // using NLog.Extensions.Logging;
namespace ProjectCruiser; namespace ProjectCruiser;
@ -22,7 +22,7 @@ public partial class ServiceForm2 : Form
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger; _logger = logger;
_logger.LogInformation("> Form is loaded successfully");
} }
// Выбор компании // Выбор компании
@ -31,57 +31,69 @@ public partial class ServiceForm2 : Form
toolPanel.Enabled = false; toolPanel.Enabled = false;
} }
// Color picker (default : random) <...>
// Добавление корабля // Добавление корабля
private void btnAddTransport_Click(object sender, EventArgs e) private void btnAddTransport_Click(object sender, EventArgs e)
{ {
EditorForm3 form3 = new(); EditorForm3 form3 = new();
// TODO передать метод :
form3.AddEvent(CreateObject); form3.AddEvent(CreateObject);
form3.Show(); form3.Show();
} }
// Создание объекта класса-перемещения // Создание объекта класса-перемещения
private void CreateObject(DrawningBase? ship) private void CreateObject(DrawningBase? ship)
{
try
{ {
if (_company == null || ship == null) if (_company == null || ship == null)
{ {
return; throw new NullReferenceException(" > No existing collections to save");
} }
if (_company + ship != -1)
{ int count = _company + ship;
MessageBox.Show("> Object was added"); MessageBox.Show("> Object was added");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("> Adding object succeed {ship} at {count} position", ship, count);
} }
else catch (Exception ex)
{ {
MessageBox.Show("[!] Failed to add object"); MessageBox.Show("[!] Failed to add object\n" + ex.Message);
_logger.LogError("< Error > : {Message}", ex.Message);
} }
} }
// Удаление объекта // Удаление объекта
private void btnRemoveCar_Click(object sender, EventArgs e) private void btnRemoveShip_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text)
|| _company == null) return; || _company == null) return;
if (MessageBox.Show("[*] Remove object: Are you sure?", "Remove", if (MessageBox.Show("[*] Remove object: Are you sure?", "Remove",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return;
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - Convert.ToInt32(maskedTextBoxPosition.Text) != null) try
{
if (_company - pos != null)
{ {
MessageBox.Show("> Object was removed"); MessageBox.Show("> Object was removed");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Object at " +
pos + "position was deleted successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("[!] Failed to remove object");
_logger.LogError("< Error > : {Message}", ex.Message);
} }
else MessageBox.Show("[!] Failed to remove object");
} }
// Передача объекта в другую форму // Передача объекта в другую форму
private void btnChooseforTest_Click(object sender, EventArgs e) private void btnChooseforTest_Click(object sender, EventArgs e)
{ {
// Add EXCEPTIONS [!]
if (_company == null) if (_company == null)
{ {
return; return;
@ -117,7 +129,6 @@ public partial class ServiceForm2 : Form
form.ShowDialog(); form.ShowDialog();
} }
// Перерисовка коллекции
private void btnRefresh_Click(object sender, EventArgs e) private void btnRefresh_Click(object sender, EventArgs e)
{ {
if (_company == null) if (_company == null)
@ -146,7 +157,17 @@ public partial class ServiceForm2 : Form
collType = CollectionType.List; collType = CollectionType.List;
} }
try
{
_storageCollection.AddCollection(maskedTxtBoxCName.Text, collType); _storageCollection.AddCollection(maskedTxtBoxCName.Text, collType);
_logger.LogInformation("Adding collection succeed : {Name}, {Type}", maskedTxtBoxCName.Text, collType);
}
catch (NullReferenceException ex)
{
Console.WriteLine(ex.Message);
_logger.LogError("< Error > : {Message}", ex.Message);
}
RefreshListBoxItems(); RefreshListBoxItems();
} }
@ -156,13 +177,21 @@ public partial class ServiceForm2 : Form
{ {
MessageBox.Show("Collection was not choosed"); MessageBox.Show("Collection was not choosed");
return; return;
} } if (MessageBox.Show("Are you sure?", "Removing",
if (MessageBox.Show("Are you sure?", "Removing", MessageBoxButtons.OK, MessageBoxIcon.Question) != DialogResult.OK) MessageBoxButtons.OK, MessageBoxIcon.Question)
!= DialogResult.OK) return;
try
{ {
return;
}
_storageCollection.DelCollection(listBox.SelectedItem.ToString()); _storageCollection.DelCollection(listBox.SelectedItem.ToString());
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Removing collection succeed : {Name}", listBox.SelectedItem.ToString);
}
catch (NullReferenceException ex)
{
Console.WriteLine(ex.Message);
_logger.LogError("< Error > : {Message}", ex.Message);
}
} }
private void RefreshListBoxItems() private void RefreshListBoxItems()
@ -235,9 +264,16 @@ public partial class ServiceForm2 : Form
try try
{ {
_storageCollection.LoadData(openFileDialog.FileName); _storageCollection.LoadData(openFileDialog.FileName);
// LoadData() : Exceptions
// FileNotFoundException
// NullReferenceException
// InvalidDataException
// IndexOutOfRangeException
// CollectionOverflowException
MessageBox.Show(" < Loaded succesfully >", MessageBox.Show(" < Loaded succesfully >",
"Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Loading from file : {filename}", openFileDialog.FileName); _logger.LogInformation("Loading from file : {Filename}", openFileDialog.FileName);
RefreshListBoxItems(); RefreshListBoxItems();
} }

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<serilog xmlns="http://www.serilog-project.org/schemas/Serilog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="shiplog-${shortdate}.log"/>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile"/>
</rules>
</serilog>
</configuration>

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}