PI-12_Zaytsev_A.V_LabWork07_Base #10

Closed
tyxzo wants to merge 2 commits from lab7 into lab6
12 changed files with 234 additions and 73 deletions

View File

@ -42,7 +42,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального кол-ва элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / (_placeSizeWidth + 75)) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@ -99,8 +99,16 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawingBus? obj = _collection?.Get(i);
obj?.DrawTrasnport(graphics);
try
{
DrawingBus? obj = _collection?.Get(i);
obj?.DrawTrasnport(graphics);
}
catch(Exception)
{
continue;
}
}
return bitmap;

View File

@ -54,8 +54,16 @@ public class BusStation : AbstractCompany
for (int i = 0, coordinate_index = 0; i < _collection.Count; i++, coordinate_index += 2)
{
_collection.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i)?.SetPosition(_arrayOfCoordinates[coordinate_index], _arrayOfCoordinates[coordinate_index + 1]);
try
{
_collection.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i)?.SetPosition(_arrayOfCoordinates[coordinate_index], _arrayOfCoordinates[coordinate_index + 1]);
}
catch (Exception)
{
break;
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using DoubleDeckerBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -38,7 +39,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
@ -47,7 +48,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
if (Count >= _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
return _collection.IndexOf(obj);
@ -55,9 +56,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Insert(T obj, int position)
{
if (Count >= _maxCount || position < 0 || position >= _maxCount)
if (position < 0 || position >= _maxCount)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (Count >= MaxCount)
{
throw new CollectionOverflowException(Count);
}
if (position > Count && position < _maxCount)
@ -65,36 +71,16 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return Insert(obj);
}
int copy_of_position = position - 1;
_collection.Insert(position, obj);
while (position < Count)
{
if (_collection[position] == null)
{
_collection.Insert(position, obj);
return position;
}
position++;
}
while (copy_of_position > 0)
{
if (_collection[copy_of_position] == null)
{
_collection.Insert(copy_of_position, obj);
return copy_of_position;
}
copy_of_position--;
}
return -1;
return position;
}
public T? Remove(int position)
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
T? removed_object = Get(position);

View File

@ -1,4 +1,5 @@
using System;
using DoubleDeckerBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -52,25 +53,35 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
return _collection[position];
}
public int Insert(T obj)
{
return Insert(obj, 0);
try
{
return Insert(obj, 0);
}
catch(CollectionOverflowException ex)
{
throw new CollectionOverflowException(ex.Message);
}
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
int copy_of_position = position - 1;
while (position < Count)
@ -92,7 +103,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
copy_of_position--;
}
return -1;
throw new CollectionOverflowException(Count);
}
@ -100,7 +111,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
T? removed_object = _collection[position];

View File

@ -1,4 +1,5 @@
using DoubleDeckerBus.Drawnings;
using DoubleDeckerBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -79,11 +80,11 @@ public class StorageCollection<T>
}
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new ArgumentException("There are no collections to save");
}
if (File.Exists(filename))
@ -127,26 +128,22 @@ public class StorageCollection<T>
sw.WriteLine(sb.ToString());
}
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("The file does not exist");
}
using (StreamReader sr = new(filename))
{
string? bufferLine = sr.ReadLine();
if (bufferLine != _collectionKey)
{
return false;
throw new ArgumentException("Invalid data in the file");
}
_storages.Clear();
@ -165,7 +162,7 @@ public class StorageCollection<T>
if (collection == null)
{
return false;
throw new ArgumentNullException("Failed to create a collection");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -176,17 +173,20 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningCar() is T car)
{
if (collection.Insert(car) == -1)
try
{
return false;
collection.Insert(car);
}
catch(CollectionOverflowException ex)
{
throw new CollectionOverflowException("The collection is overflowing", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
}
/// <summary>

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="7.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +34,12 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties /></VisualStudio></ProjectExtensions>
</Project>

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 DoubleDeckerBus.Exceptions;
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("The allowed amount in the collection has been exceeded: " + 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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus.Exceptions;
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("The object was not found by position " + 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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus.Exceptions;
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Going beyond the boundaries of the collection. Position: " + 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,5 +1,6 @@
using DoubleDeckerBus.CollectionGenericObjects;
using DoubleDeckerBus.Drawnings;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -18,13 +19,16 @@ public partial class FormBusCollection : Form
private readonly StorageCollection<DrawingBus> _storageCollection;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormBusCollection()
public FormBusCollection(ILogger<FormBusCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e)
@ -46,14 +50,20 @@ public partial class FormBusCollection : Form
return;
}
if ((_company + bus) != -1)
try
{
MessageBox.Show("Object added");
pictureBox.Image = _company.Show();
if ((_company + bus) != -1)
{
MessageBox.Show("Object added");
pictureBox.Image = _company.Show();
_logger.LogInformation("Object added: {obj}", bus.GetDataForSave());
}
}
else
catch (Exception ex)
{
MessageBox.Show("Failed to add object");
MessageBox.Show(ex.Message);
_logger.LogError("Failed to add object", ex.Message);
}
}
@ -72,16 +82,19 @@ public partial class FormBusCollection : Form
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
try
{
DrawingBus? removedObj = _company - pos;
MessageBox.Show("Object removed");
pictureBox.Image = _company.Show();
_logger.LogInformation("Object removed {obj}", removedObj?.GetDataForSave());
}
else
catch(Exception ex)
{
MessageBox.Show("Failed to remove object");
MessageBox.Show(ex.Message);
_logger.LogError("Failed to remove object", ex.Message);
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
@ -130,6 +143,7 @@ public partial class FormBusCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonArray.Checked && !radioButtonList.Checked))
{
MessageBox.Show("Not all data is filled in", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Failed to add collection: not all data is filled in");
return;
}
@ -144,6 +158,7 @@ public partial class FormBusCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Added a collection of type {type} with the name {name}", collectionType, textBoxCollectionName.Text);
RefreshListBoxItems();
}
@ -165,6 +180,7 @@ public partial class FormBusCollection : Form
if (listBoxCollectionItems.SelectedIndex < 0)
{
MessageBox.Show("No collection selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Failed to remove collection: no collection selected");
return;
}
@ -175,6 +191,7 @@ public partial class FormBusCollection : Form
if (result == DialogResult.Yes)
{
_storageCollection.DelCollection(listBoxCollectionItems.Text);
_logger.LogInformation("Removed a collection {name}: ", listBoxCollectionItems.SelectedItem?.ToString());
RefreshListBoxItems();
}
else
@ -211,31 +228,37 @@ public partial class FormBusCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Save succeeded", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Saving to the file: {filename}", saveFileDialog.FileName);
}
else
catch(Exception ex)
{
MessageBox.Show("Unable to save", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Error: {Message}", ex.Message);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Load succeeded", "Resilt", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Loading from the file: {filename}", openFileDialog.FileName);
RefreshListBoxItems();
}
else
catch(Exception ex)
{
MessageBox.Show("Unable to load", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Error: {Message}", ex.Message);
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace DoubleDeckerBus
{
internal static class Program
@ -11,7 +16,23 @@ namespace DoubleDeckerBus
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormBusCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider servicesProvider = services.BuildServiceProvider();
Application.Run(servicesProvider.GetRequiredService<FormBusCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBusCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("serilog.json").Build()).CreateLogger());
});
}
}
}

View File

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