PIBD-13_Fomichev_V.S._LabWork07_Simple_ #8

Closed
slavaxom9k wants to merge 4 commits from labwork07 into labwork06
7 changed files with 148 additions and 80 deletions
Showing only changes of commit 9699679939 - Show all commits

View File

@ -9,8 +9,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="Serilog" Version="3.1.1" />
</ItemGroup>
<ItemGroup>

View File

@ -1,5 +1,6 @@
using AntiAircraftGun.CollectionGenereticObject;
using AntiAircraftGun.Exceptions;
using Exceptions;
namespace AntiAircraftGun.CollectionGenericObjects;
/// <summary>
@ -48,29 +49,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Get(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (_collection[position] == null) throw new ObjectNotFoundException();
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (Count == _maxCount) throw new CollectionOverflowException();
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count == _maxCount) throw new CollectionOverflowException();
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;

View File

@ -52,7 +52,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
@ -69,48 +70,59 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
throw new CollectionOverflowException();
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (_collection[position] == null)
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
{
_collection[position] = obj;
return position;
}
int temp = position + 1;
while (temp < Count)
{
if (_collection[temp] == null)
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
_collection[temp] = obj;
return temp;
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
++temp;
}
temp = position - 1;
while (temp >= 0)
{
if (_collection[temp] == null)
if (!pushed)
{
_collection[temp] = obj;
return temp;
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
--temp;
}
throw new CollectionOverflowException();
// вставка
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
T? myObject = _collection[position];
if (myObject == null) throw new ObjectNotFoundException();
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return myObject;
return temp;
}
public IEnumerable<T?> GetItems()

View File

@ -1,8 +1,10 @@
using AntiAircraftGun.CollectionGenereticObject;
using NLog.LayoutRenderers.Wrappers;
using AntiAircraftGun.CollectionGenereticObject;
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.Exceptions;
using System.Text;
namespace AntiAircraftGun.CollectionGenericObjects;
/// <summary>
@ -93,26 +95,23 @@ public class StorageCollection<T>
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
Review

Требовалось заменить класс Exception на его более подходящих наследников

Требовалось заменить класс Exception на его более подходящих наследников
}
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter writer = new(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
@ -127,7 +126,6 @@ public class StorageCollection<T>
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
@ -150,11 +148,12 @@ public class StorageCollection<T>
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
throw new Exception("Файл не подходит");
throw new IOException("Файл не подходит");
}
if (!line.Equals(_collectionKey))
{
throw new Exception("В файле неверные данные");
throw new IOException("В файле неверные данные");
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
@ -182,7 +181,7 @@ public class StorageCollection<T>
{
if (collection.Insert(truck) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: ");
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
@ -194,6 +193,7 @@ public class StorageCollection<T>
_storages.Add(record[0], collection);
}
}
}
/// <summary>

View File

@ -2,6 +2,7 @@
using AntiAircraftGun.CollectionGenereticObjects;
using AntiAircraftGun.CollectionGenericObjects;
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.Exceptions;
using Microsoft.Extensions.Logging;
namespace AntiAircraftGun;
@ -51,26 +52,30 @@ public partial class FormArmoredCarCollection : Form
private void buttonAddArmoredCar_Click(object sender, EventArgs e)
{
FormCarConfig form = new();
// TODO передать метод
form.Show();
form.AddEvent(SetCar);
}
/// <summary>
/// Добавление машины в коллеуции
/// Добавление машины в коллекции
/// </summary>
/// <param name="armoredCar"></param>
private void SetCar(DrawningArmoredCar? armoredCar)
{
if (_company == null || armoredCar == null)
try
{
return;
if (_company == null || armoredCar == null)
{
return;
}
if (_company + armoredCar != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
}
if (_company + armoredCar != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
catch (CollectionOverflowException)
{
MessageBox.Show("Не удалось добавить объект");
}
@ -84,7 +89,7 @@ public partial class FormArmoredCarCollection : Form
/// <param name="e"></param>
private void buttonRemoveArmoredCar_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
@ -92,15 +97,26 @@ public partial class FormArmoredCarCollection : Form
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (PositionOutOfCollectionException)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Ошибка при удалении объекта");
}
catch (Exception)
{
MessageBox.Show("Неизвестная ошибка при удалении объекта");
}
}
@ -115,8 +131,13 @@ public partial class FormArmoredCarCollection : Form
{
return;
}
try
{
pictureBox.Image = _company.Show();
pictureBox.Image = _company.Show();
}
catch (PositionOutOfCollectionException) { }
catch (Exception) { }
}
/// <summary>
@ -236,12 +257,19 @@ public partial class FormArmoredCarCollection : Form
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
try
{
case "Хранилище":
_company = new CarBase(pictureBox.Width, pictureBox.Height, collection);
break;
switch (comboBoxSelectorCompany.Text)
{
case "База":
_company = new CarBase(pictureBox.Width, pictureBox.Height, collection);
break;
}
}
catch (ObjectNotFoundException)
{
}
panelCompanyTools.Enabled = true;

View File

@ -1,24 +1,25 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace AntiAircraftGun
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
var services = new ServiceCollection();
ConfigureService(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormArmoredCarCollection>());
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormArmoredCarCollection>());
}
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
@ -28,16 +29,16 @@ namespace AntiAircraftGun
{
services
.AddSingleton<FormArmoredCarCollection>()
.AddLogging(option => {
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
//option.AddSerilog(new LoggerConfiguration()
// //.WriteTo
// .CreateLogger());
option.AddNLog("serilog.config");
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
}
}
}

View File

@ -0,0 +1,25 @@
{
"AllowedHosts": "*",
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "C:\\Users\\ipazu\\Desktop\\log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} | {Level:u} | {SourceContext} | {Message:1j}{NewLine}{Exception}"
}
}
]
}
}