Лабораторная работа №7

This commit is contained in:
mara-1 2024-05-10 07:38:38 +04:00
parent 183f1928ae
commit 604b8d9d44
15 changed files with 441 additions and 80 deletions

View File

@ -1,4 +1,5 @@
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -95,12 +96,25 @@ public abstract class AbstractCompany
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningTrackedMachine? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{
}
catch (PositionOutOfCollectionException e)
{
}
}
return bitmap;
}

View File

@ -1,4 +1,5 @@
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -35,18 +36,26 @@ public class Garage : AbstractCompany
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
DrawningTrackedMachine? drawningTrackedMachine = _collection?.Get(n);
n++;
if (drawningTrackedMachine != null)
try
{
DrawningTrackedMachine? drawingMachine = _collection?.Get(n);
if (drawingMachine != null)
{
drawingMachine.SetPictureSize(_pictureWidth, _pictureHeight);
drawingMachine.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
catch (ObjectNotFoundException e)
{
}
catch (PositionOutOfCollectionException e)
{
drawningTrackedMachine.SetPictureSize(_pictureWidth, _pictureHeight);
drawningTrackedMachine.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
n++;
}
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectBulldozer.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -64,16 +65,16 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (Count + 1 > _maxCount) return -1;
if (position < 0 || position > Count) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return 1;
return position;
}
public T? Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position < 0 || position > Count) return null;
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T? temp = _collection[position];
_collection.RemoveAt(position);
return temp;

View File

@ -1,4 +1,5 @@
using System;
using ProjectBulldozer.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -53,13 +54,10 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO проверка позиции
if (position <= Count)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
else
return null;
}
public int Insert(T obj)
{
// TODO вставка в свободное место набора
@ -71,7 +69,7 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
@ -81,39 +79,55 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// ищется свободное место после этой позиции и идет туда
// если нет после, ищем до
// TODO вставка
if (position < Count)
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
{
if (position < 0 || position >= Count)
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
return -1;
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
if (_collection[position] == null)
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
// вставка
_collection[position] = obj;
return position;
}
else
{
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
}
}
return -1;
}
public T? Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= Count || position < 0) return null;
T? myObject = _collection[position];
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,4 +1,6 @@
using ProjectBulldozer.Drawnings;
using ProjectBulldozer.Exceptions;
using ProjectElectroTrans.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -100,7 +102,7 @@ internal class StorageCollection<T>
{
if (_storages.Count == 0)
{
return false;
throw new EmptyFileExeption();
}
if (File.Exists(filename))
@ -115,7 +117,6 @@ internal class StorageCollection<T>
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
@ -135,15 +136,16 @@ internal class StorageCollection<T>
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
return true;
return true;
}
/// <summary>
@ -161,14 +163,17 @@ internal class StorageCollection<T>
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
if (string.IsNullOrEmpty(str))
{
return false;
throw new FileNotFoundException(filename);
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new FileFormatException(filename);
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
@ -178,26 +183,91 @@ internal class StorageCollection<T>
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningMachine() is T machine)
if (elem?.CreateDrawningMachine() is T ship)
{
if (collection.Insert(machine) == -1)
try
{
return false;
collection.Insert(ship);
}
catch (Exception ex)
{
throw new FileFormatException(filename, ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
if (!File.Exists(filename))
{
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (string.IsNullOrEmpty(str))
{
throw new EmptyFileExeption(filename);
}
if (!str.StartsWith(_collectionKey))
{
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningMachine() is T ship)
{
try
{
if (collection.Insert(ship) == -1)
{
throw new CollectionTypeException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw ex.InnerException!;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectBulldozer.Exceptions;
[Serializable]
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception) { }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[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

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
using ProjectBulldozer.CollectionGenericObjects;
namespace ProjectBulldozer.Exceptions;
[Serializable]
public class CollectionTypeException : Exception
{
public CollectionTypeException() : base() { }
public CollectionTypeException(string message) : base(message) { }
public CollectionTypeException(string message, Exception exception) :
base(message, exception) { }
protected CollectionTypeException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class EmptyFileExeption : Exception
{
public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { }
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileExeption(string name, string message) : base(message) { }
public EmptyFileExeption(string name, string message, Exception exception) :
base(message, exception) { }
protected EmptyFileExeption(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Exceptions;
[Serializable]
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
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

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Exceptions;
[Serializable]
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
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

@ -1,4 +1,5 @@
using ProjectBulldozer.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectBulldozer.CollectionGenericObjects;
using ProjectBulldozer.Drawnings;
using System;
using System.Collections.Generic;
@ -27,15 +28,22 @@ public partial class FormMachineCollectoin : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMachineCollectoin()
public FormMachineCollectoin(ILogger<FormMachineCollectoin> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
/// </summary>
@ -43,7 +51,13 @@ public partial class FormMachineCollectoin : Form
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
panelCompanyTools.Enabled = false; switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new Garage(pictureBox.Width, pictureBox.Height,
new MassiveGenericObjects<DrawningTrackedMachine>());
break;
}
}
/// <summary>
@ -55,8 +69,9 @@ public partial class FormMachineCollectoin : Form
{
FormMachineConfig form = new();
form.AddEvent(SetMachine);
form.Show();
form.AddEvent(SetMachine);
}
/// <summary>
@ -69,14 +84,18 @@ public partial class FormMachineCollectoin : Form
{
return;
}
if (_company + trackedMachine != -1)
try
{
var res = _company + trackedMachine;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
@ -101,14 +120,18 @@ public partial class FormMachineCollectoin : Form
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -187,10 +210,18 @@ public partial class FormMachineCollectoin : Form
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text,
collectionType);
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
/// Удаление коллекции
@ -272,13 +303,19 @@ public partial class FormMachineCollectoin : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.SaveData(saveFileDialog.FileName);
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($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -294,16 +331,20 @@ public partial class FormMachineCollectoin : Form
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка прошла успешно в {openFileDialog.FileName}");
RerfreshListBoxItems();
}
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

@ -1,3 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
using System;
namespace ProjectBulldozer
{
internal static class Program
@ -11,7 +17,33 @@ namespace ProjectBulldozer
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMachineCollectoin());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMachineCollectoin>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMachineCollectoin>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}serilog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -8,6 +8,33 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="8.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" 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="Microsoft.IdentityModel.JsonWebTokens" Version="7.5.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.2" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Expressions" Version="4.0.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Trace" Version="3.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.5.1" />
<PackageReference Include="System.Text.Json" Version="8.0.3" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +50,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,21 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
},
{ "Name": "Console" }
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Locomotives"
}
}
}