5 Commits
Lab-5 ... Lab-7

Author SHA1 Message Date
fd88fea05f Lab 7 done 2024-05-15 17:20:36 +04:00
326e4cf801 Final version 2024-04-20 09:16:18 +04:00
cf07e0696e removing unnecessary checks 2024-04-20 08:45:20 +04:00
cc1aa1d3d6 Cleaning excessive files 2024-04-20 00:24:34 +04:00
def409392f Lab-6 done 2024-04-20 00:22:42 +04:00
22 changed files with 601 additions and 78 deletions

View File

@@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.Drawings;
namespace Catamaran
{
public delegate void BoatDelegate(DrawingBoat boat);
}

View File

@@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</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" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<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>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +34,13 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -27,7 +27,7 @@ namespace Catamaran.CollectionGenericObjects
_pictureHeight = picHeight;
_pictureWidth = picWidth;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
public static int operator +(AbstractCompany company, DrawingBoat boat)

View File

@@ -1,4 +1,5 @@
using System;
using Catamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -13,8 +14,13 @@ namespace Catamaran.CollectionGenericObjects
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -31,6 +37,8 @@ namespace Catamaran.CollectionGenericObjects
}
}
public CollectionType GetCollectionType => CollectionType.Array;
public ArrayGenericObjects()
{
_collection = Array.Empty<T?>();
@@ -42,7 +50,7 @@ namespace Catamaran.CollectionGenericObjects
{
return _collection[position];
}
return null;
throw new PositionOutOfRangeException(position) ;
}
public int Insert(T obj)
@@ -55,31 +63,31 @@ namespace Catamaran.CollectionGenericObjects
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < Count || position >= 0)
if (position > Count || position < 0)
{
if (_collection[position] == null)
throw new PositionOutOfRangeException(position);
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
else
else
{
for (int i = 0; i < Count; i++)
{
for (int i = 0; i < Count; i++)
if (_collection[i] == null)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
_collection[i] = obj;
return i;
}
}
}
return -1;
}
@@ -87,12 +95,20 @@ namespace Catamaran.CollectionGenericObjects
{
if (position > Count || position < 0)
{
return null;
throw new PositionOutOfRangeException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException();
T? obj = _collection[position];
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
}
}

View File

@@ -11,7 +11,7 @@ namespace Catamaran.CollectionGenericObjects
{
int Count { get; }
int SetMaxCount { set; }
int MaxCount { get; set; }
int Insert(T obj);
@@ -20,5 +20,9 @@ namespace Catamaran.CollectionGenericObjects
T? Remove(int position);
T? Get(int position);
CollectionType GetCollectionType { get; }
IEnumerable<T?> GetItems();
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Catamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -16,7 +17,24 @@ namespace Catamaran.CollectionGenericObjects
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get
{
if (_maxCount < _collection.Count) return _maxCount;
return _collection.Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public ListGenericObjects()
{
@@ -25,28 +43,27 @@ namespace Catamaran.CollectionGenericObjects
public T? Get(int position)
{
if (position < 0 || position >= Count)
{
return null;
}
if (position >= Count || position < 0) throw new PositionOutOfRangeException(position);
if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position];
}
public int Insert(T obj)
{
if (Count + 1 > _maxCount)
{
return -1;
}
if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return 1;
}
public int Insert(T obj, int position)
{
if (position < 0 || position > Count || Count + 1 > _maxCount)
if (position < 0 || position > Count)
{
return -1;
throw new PositionOutOfRangeException(position);
}
if (Count + 1 > _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
return 1;
@@ -56,11 +73,19 @@ namespace Catamaran.CollectionGenericObjects
{
if (position < 0 || position > Count)
{
return null;
throw new PositionOutOfRangeException(position);
}
T? obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; i++)
{
yield return _collection[i];
}
}
}
}

View File

@@ -1,6 +1,8 @@
using Catamaran.Drawings;
using Catamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -8,12 +10,18 @@ using System.Threading.Tasks;
namespace Catamaran.CollectionGenericObjects
{
public class StorageCollection<T>
where T : class
where T : DrawingBoat
{
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
public List<string> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorKeyValue = "|";
private readonly string _separatorItems = ";";
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
@@ -58,5 +66,128 @@ namespace Catamaran.CollectionGenericObjects
return _storages[name];
}
}
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
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(_separatorKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
writer.Close();
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует!");
}
using (StreamReader reader = new(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
throw new ArgumentException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
{
string[] record = line.Split(_separatorKeyValue, 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)
{
throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingBoat() is T boat)
{
try
{
if (collection.Insert(boat) < 0)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Array => new ArrayGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}
}

View File

@@ -47,6 +47,12 @@ namespace Catamaran.Drawings
}
public DrawingBoat(EntityBoat? entityBoat) : this()
{
if (entityBoat == null) return;
EntityBoat = new EntityBoat(entityBoat.Speed, entityBoat.Weight, entityBoat.BodyColor);
}
protected DrawingBoat(int drawingCatamaranWidth, int drawingCatamaranHeight) : this()
{
_drawingCatamaranWidth = drawingCatamaranWidth;

View File

@@ -17,6 +17,12 @@ namespace Catamaran.Drawings
EntityBoat = new EntityCatamaran(speed, weight, bodyColor, additionalColor, leftBobber, rightBobber, sail);
}
public DrawingCatamaran(EntityCatamaran? entityCatamaran) : base(120, 90)
{
if (entityCatamaran == null) return;
EntityBoat = new EntityCatamaran(entityCatamaran.Speed, entityCatamaran.Weight, entityCatamaran.BodyColor,
entityCatamaran.AdditionalColor, entityCatamaran.LeftBobber, entityCatamaran.RightBobber, entityCatamaran.Sail);
}
public override void DrawTransport(Graphics g)
{

View File

@@ -0,0 +1,42 @@
using Catamaran.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Drawings
{
public static class ExtentionDrawingBoat
{
private static readonly string _separator = ":";
public static DrawingBoat? CreateDrawingBoat(this string info)
{
string[] strs = info.Split(_separator);
EntityBoat? boat = EntityCatamaran.CreateEntityCatamaran(strs);
if (boat != null)
{
return new DrawingCatamaran((EntityCatamaran)boat);
}
boat = EntityBoat.CreateEntityBoat(strs);
if (boat != null)
{
return new DrawingBoat(boat);
}
return null;
}
public static string GetDataForSave(this DrawingBoat drawingBoat)
{
string[]? array = drawingBoat?.EntityBoat?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separator, array);
}
}
}

View File

@@ -24,6 +24,21 @@ namespace Catamaran.Entities
AdditionalColor = addColor;
}
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityCatamaran), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, LeftBobber.ToString(), RightBobber.ToString(), Sail.ToString() };
}
public static EntityCatamaran? CreateEntityCatamaran(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityCatamaran))
{
return null;
}
return new EntityCatamaran(Convert.ToInt32(strs[1]),
Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
public EntityCatamaran(int speed, double weight, Color bodyColor, Color additionalColor, bool leftBobber, bool rightBobber, bool sail) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;

View File

@@ -21,6 +21,22 @@ namespace Catamaran.Entities
BodyColor = color;
}
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityBoat), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
public static EntityBoat? CreateEntityBoat(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityBoat))
{
return null;
}
return new EntityBoat(Convert.ToInt32(strs[1]),
Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
public EntityBoat(int speed, double weight, Color bodyColor)
{
Speed = speed;

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Exceptions
{
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("Превышено количество элементов коллекции: count" + count) { }
public CollectionOverflowException() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.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 context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Exceptions
{
[Serializable]
internal class PositionOutOfRangeException : ApplicationException
{
public PositionOutOfRangeException(int i) : base("Не найден объект по позиции " + i) { }
public PositionOutOfRangeException() : base() { }
public PositionOutOfRangeException(string message) : base(message) { }
public PositionOutOfRangeException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -46,10 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip1 = new MenuStrip();
FileToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBox1.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelCollection.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// groupBox1
@@ -59,9 +66,9 @@
groupBox1.Controls.Add(panelCollection);
groupBox1.Controls.Add(comboBoxSelectorCompany);
groupBox1.Dock = DockStyle.Right;
groupBox1.Location = new Point(809, 0);
groupBox1.Location = new Point(814, 28);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(237, 642);
groupBox1.Size = new Size(237, 646);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
@@ -75,7 +82,7 @@
panelCompanyTools.Controls.Add(DeleteButton);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 398);
panelCompanyTools.Location = new Point(3, 402);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(231, 241);
panelCompanyTools.TabIndex = 9;
@@ -235,19 +242,63 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(809, 642);
pictureBox.Size = new Size(814, 646);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1051, 28);
menuStrip1.TabIndex = 2;
menuStrip1.Text = "menuStrip1";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(59, 24);
FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
SaveToolStripMenuItem.Size = new Size(216, 26);
SaveToolStripMenuItem.Text = "Сохранить";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
LoadToolStripMenuItem.Size = new Size(216, 26);
LoadToolStripMenuItem.Text = "Загрузить";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// FormBoatColletion
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1046, 642);
ClientSize = new Size(1051, 674);
Controls.Add(pictureBox);
Controls.Add(groupBox1);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormBoatColletion";
Text = "Коллекция лодок";
groupBox1.ResumeLayout(false);
@@ -256,7 +307,10 @@
panelCollection.ResumeLayout(false);
panelCollection.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -279,5 +333,11 @@
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private Panel panelCompanyTools;
private MenuStrip menuStrip1;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@@ -1,6 +1,9 @@
using Catamaran.CollectionGenericObjects;
using Catamaran.Drawings;
using Catamaran.Exceptions;
using Microsoft.Extensions.Logging;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -19,10 +22,13 @@ namespace Catamaran
private readonly StorageCollection<DrawingBoat> _storageCollection;
public FormBoatColletion()
private readonly ILogger _logger;
public FormBoatColletion(ILogger<FormBoatColletion> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
@@ -30,7 +36,7 @@ namespace Catamaran
panelCompanyTools.Enabled = false;
}
private void AddBoatButton_Click(object sender, EventArgs e)
{
@@ -50,14 +56,17 @@ namespace Catamaran
return;
}
if (_company + boat >= 0)
try
{
int addingObj = _company + boat;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {boat.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект {ex.Message}");
}
}
@@ -86,14 +95,22 @@ namespace Catamaran
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
try
{
object delObj = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show();
}
else
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект по позиции {pos}");
}
catch (PositionOutOfRangeException)
{
MessageBox.Show("Удаление вне рамкок коллекции");
_logger.LogWarning($"Не удалось удалить объект по позиции {pos} - вне коллекции");
}
}
@@ -112,27 +129,34 @@ namespace Catamaran
{
return;
}
DrawingBoat? boat = null;
int counter = 100;
while (boat == null)
try
{
boat = _company.GetRandomObject();
DrawingBoat? boat = null;
int counter = 100;
while (boat == null)
{
boat = _company.GetRandomObject();
counter--;
if (counter <= 0) break;
}
counter--;
if (boat == null)
{
return;
}
if (counter <= 0) break;
}
if (boat == null)
{
throw new ObjectNotFoundException();
}
FormCatamaran form = new()
{
SetBoat = boat
};
form.ShowDialog();
FormCatamaran form = new()
{
SetBoat = boat
};
form.ShowDialog();
}
catch (ObjectNotFoundException)
{
_logger.LogWarning($"Не удалось найти объект для отправки на тест");
}
}
private void RefreshListBoxItems()
@@ -153,6 +177,7 @@ namespace Catamaran
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonArray.Checked && !radioButtonList.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Неверно введены данные для создания коллекции");
return;
}
@@ -167,6 +192,7 @@ namespace Catamaran
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция - {textBoxCollectionName.Text}");
RefreshListBoxItems();
}
@@ -175,13 +201,16 @@ namespace Catamaran
if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Не выбрана коллекция");
_logger.LogWarning("Ошибка удаления коллекции - она не выбрана");
return;
}
string temp = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция - {temp}");
RefreshListBoxItems();
}
@@ -190,6 +219,7 @@ namespace Catamaran
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Ошибка создания компании - она не выбрана");
return;
}
@@ -197,6 +227,7 @@ namespace Catamaran
if (collection == null)
{
MessageBox.Show("Коллекция не инициализирована");
_logger.LogWarning("Ошибка инициализации коллекции");
return;
}
@@ -211,6 +242,44 @@ namespace Catamaran
RefreshListBoxItems();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Успешно сохранено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка сохранения: {Message}", ex.Message);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Успешно загружено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка загрузки: {Message}", ex.Message);
}
}
}
}
}

View File

@@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>318, 17</value>
</metadata>
</root>

View File

@@ -143,9 +143,5 @@ namespace Catamaran
}
}
private void panelWhite_Paint(object sender, PaintEventArgs e)
{
}
}
}

View File

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

View File

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

View File

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