diff --git a/ZeroExample/App.config b/ZeroExample/App.config new file mode 100644 index 0000000..f0a74bb --- /dev/null +++ b/ZeroExample/App.config @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ZeroExample/Program.cs b/ZeroExample/Program.cs new file mode 100644 index 0000000..a846279 --- /dev/null +++ b/ZeroExample/Program.cs @@ -0,0 +1,26 @@ +using ZeroLevel; +using ZeroLevel.Services.Applications; + +namespace ZeroExample +{ + public sealed class MyFirstApp + : BaseWindowsService, IZeroService + { + public MyFirstApp() : base("MyApp") { Log.AddConsoleLogger(); } + public override void PauseAction() { } + public override void ResumeAction() { } + public override void StartAction() + { + Log.Info("Started"); + } + public override void StopAction() { } + } + + class Program + { + static void Main(string[] args) + { + Bootstrap.Startup(args); + } + } +} diff --git a/ZeroExample/Properties/AssemblyInfo.cs b/ZeroExample/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a825422 --- /dev/null +++ b/ZeroExample/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ZeroExample")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ZeroExample")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("50cebec2-2571-4592-afd2-970bdb41947b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ZeroExample/ZeroExample.csproj b/ZeroExample/ZeroExample.csproj new file mode 100644 index 0000000..4734f4b --- /dev/null +++ b/ZeroExample/ZeroExample.csproj @@ -0,0 +1,62 @@ + + + + + Debug + AnyCPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B} + Exe + ZeroExample + ZeroExample + v4.7.2 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + ..\packages\ZeroLevel.1.0.3\lib\net47\ZeroLevel.dll + + + + + Component + + + + + + Designer + + + + + \ No newline at end of file diff --git a/ZeroExample/packages.config b/ZeroExample/packages.config new file mode 100644 index 0000000..c024b44 --- /dev/null +++ b/ZeroExample/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache b/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache index 7a6e9ee..ffd6fd9 100644 --- a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache +++ b/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -02ab5562f7a9f633d41e073aff759527ff59696c +4f0bbfe8ac44b56784f7eeaa3cdef96609d6b97e diff --git a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache b/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache index 86a36f8..9b98d20 100644 Binary files a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache and b/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache differ diff --git a/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csproj.CoreCompileInputs.cache b/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csproj.CoreCompileInputs.cache index d40012b..104314d 100644 --- a/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csproj.CoreCompileInputs.cache +++ b/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -1a68033c72e3e719a45c8165f48f4effb88b5e68 +48781ba1f58e845d50aedda0cbff5881dfe0563f diff --git a/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csprojAssemblyReference.cache b/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csprojAssemblyReference.cache index dec9983..3d9d0c1 100644 Binary files a/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csprojAssemblyReference.cache and b/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csprojAssemblyReference.cache differ diff --git a/ZeroLevel.sln b/ZeroLevel.sln index c2f94eb..aef504b 100644 --- a/ZeroLevel.sln +++ b/ZeroLevel.sln @@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZeroLevel.Microservices", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZeroLevel.Discovery", "ZeroLevel.Discovery\ZeroLevel.Discovery.csproj", "{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZeroExample", "ZeroExample\ZeroExample.csproj", "{50CEBEC2-2571-4592-AFD2-970BDB41947B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -55,6 +57,18 @@ Global {4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Release|x64.Build.0 = Release|Any CPU {4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Release|x86.ActiveCfg = Release|Any CPU {4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Release|x86.Build.0 = Release|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Debug|x64.ActiveCfg = Debug|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Debug|x64.Build.0 = Debug|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Debug|x86.ActiveCfg = Debug|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Debug|x86.Build.0 = Debug|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Release|Any CPU.Build.0 = Release|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Release|x64.ActiveCfg = Release|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Release|x64.Build.0 = Release|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Release|x86.ActiveCfg = Release|Any CPU + {50CEBEC2-2571-4592-AFD2-970BDB41947B}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZeroLevel/Models/BaseModel.cs b/ZeroLevel/Models/BaseModel.cs index f2c8c2e..41591e7 100644 --- a/ZeroLevel/Models/BaseModel.cs +++ b/ZeroLevel/Models/BaseModel.cs @@ -10,7 +10,7 @@ namespace ZeroLevel.Models #region Equal public bool Equals(BaseModel other) { - if (this == null) // и так бывает + if (this == null) throw new NullReferenceException(); if (other == null) return false; diff --git a/ZeroLevel/Models/BinaryDocument.cs b/ZeroLevel/Models/BinaryDocument.cs index ae76f40..e4687b7 100644 --- a/ZeroLevel/Models/BinaryDocument.cs +++ b/ZeroLevel/Models/BinaryDocument.cs @@ -6,7 +6,7 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel.Models { /// - /// Документ в бинарном представлении + /// Binary data represantation /// public class BinaryDocument : IBinarySerializable, @@ -14,31 +14,31 @@ namespace ZeroLevel.Models ICloneable { /// - /// Идентификатор + /// Id /// public Guid Id { get; set; } /// - /// Имя файла + /// File name /// public string FileName { get; set; } /// - /// Тип содержимого (pdf, doc и т.п.) + /// Content type (pdf, doc, etc.) /// public string ContentType { get; set; } /// - /// Содержимое + /// Content /// public byte[] Document { get; set; } /// - /// Дата создания + /// Creation date /// public DateTime Created { get; set; } /// - /// Опциональные заголовки + /// Optional headers /// public List
Headers { get; set; } /// - /// Категории + /// Categories /// public List Categories { get; set; } diff --git a/ZeroLevel/Models/InvokeResult.cs b/ZeroLevel/Models/InvokeResult.cs index 2ec5753..d66280a 100644 --- a/ZeroLevel/Models/InvokeResult.cs +++ b/ZeroLevel/Models/InvokeResult.cs @@ -5,7 +5,7 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel.Models { /// - /// Результат выполнения действий + /// Action result /// [DataContract] public class InvokeResult : @@ -29,12 +29,12 @@ namespace ZeroLevel.Models #region Properties /// - /// Успех выполнения операции + /// true when action successfully invoked /// [DataMember] public bool Success; /// - /// Комментарий (сообщение об ошибке при сбое, или доп. информация) + /// Comment /// [DataMember] public string Comment; @@ -42,15 +42,15 @@ namespace ZeroLevel.Models #region Fabric methods /// - /// Сбой при выполнении плана действий + /// Error when action invoking /// public static InvokeResult Fault(string comment) { return new InvokeResult(false, comment); } /// - /// Успешное выполнение + /// Successfully /// public static InvokeResult Succeeding(string comment = "") { return new InvokeResult(true, comment); } /// - /// Успешное выполнение + /// Successfully /// public static InvokeResult Succeeding() { return _successResultWitoutComment; } #endregion @@ -91,7 +91,7 @@ namespace ZeroLevel.Models #region Fabric methods public static InvokeResult Succeeding(T value, string comment = "") { return new InvokeResult(value, true, comment); } - public static InvokeResult Fault(string comment) { return new InvokeResult(false, comment); } + public static InvokeResult Fault(string comment) { return new InvokeResult(false, comment); } #endregion public override void Serialize(IBinaryWriter writer) diff --git a/ZeroLevel/Services/Application/BaseWindowsService.cs b/ZeroLevel/Services/Application/BaseWindowsService.cs index ffbd7dd..27859c5 100644 --- a/ZeroLevel/Services/Application/BaseWindowsService.cs +++ b/ZeroLevel/Services/Application/BaseWindowsService.cs @@ -54,7 +54,7 @@ namespace ZeroLevel.Services.Applications } catch (Exception ex) { - Log.SystemFatal(ex, $"[{Name}] Failed to start service"); + Log.Fatal(ex, $"[{Name}] Failed to start service"); Stop(); } } @@ -72,7 +72,7 @@ namespace ZeroLevel.Services.Applications } catch (Exception ex) { - Log.SystemFatal(ex, $"[{Name}] Failed to pause service"); + Log.Fatal(ex, $"[{Name}] Failed to pause service"); Stop(); } } @@ -90,7 +90,7 @@ namespace ZeroLevel.Services.Applications } catch (Exception ex) { - Log.SystemFatal(ex, $"[{Name}] Failed to continue work service after pause"); + Log.Fatal(ex, $"[{Name}] Failed to continue work service after pause"); Stop(); } } @@ -108,7 +108,7 @@ namespace ZeroLevel.Services.Applications } catch (Exception ex) { - Log.SystemFatal(ex, $"[{Name}] Failed to stop service"); + Log.Fatal(ex, $"[{Name}] Failed to stop service"); } finally { diff --git a/ZeroLevel/Services/Application/BusinessApplication.cs b/ZeroLevel/Services/Application/BusinessApplication.cs index 899fff6..55cea17 100644 --- a/ZeroLevel/Services/Application/BusinessApplication.cs +++ b/ZeroLevel/Services/Application/BusinessApplication.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; using System.Reflection; using System.ServiceProcess; using ZeroLevel.Services.Applications; @@ -10,7 +11,7 @@ namespace ZeroLevel { static Bootstrap() { - // Хак, чтобы не переписывать runtime секцию конфига при каждом обновлении Newtonsoft пакета + // Tricks for minimize config changes for dependency resolve AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } @@ -27,6 +28,11 @@ namespace ZeroLevel { return Assembly.LoadFile(Path.Combine(Configuration.BaseDirectory, "Microsoft.Owin.dll")); } + var candidates = Directory.GetFiles(Path.Combine(Configuration.BaseDirectory), args.Name, SearchOption.TopDirectoryOnly); + if (candidates != null && candidates.Any()) + { + return Assembly.LoadFile(candidates.First()); + } } catch (Exception ex) { @@ -36,7 +42,7 @@ namespace ZeroLevel } /// - /// Установка приложения в качестве службы + /// Self-install as windows service /// private static void InstallApplication() { @@ -48,11 +54,11 @@ namespace ZeroLevel } catch (Exception ex) { - Log.SystemFatal(ex, "[Bootstrap] Fault service install"); + Log.Fatal(ex, "[Bootstrap] Fault service install"); } } /// - /// Удаление приложения из служб + /// Uninstall from windows services /// private static void UninstallApplication() { @@ -64,7 +70,7 @@ namespace ZeroLevel } catch (Exception ex) { - Log.SystemFatal(ex, "[Bootstrap] Fault service uninstall"); + Log.Fatal(ex, "[Bootstrap] Fault service uninstall"); } } @@ -125,7 +131,6 @@ namespace ZeroLevel return; } } - // Исключения в процессе работы приложения перехыватываются уровнем ниже if (Environment.UserInteractive) { try @@ -136,7 +141,7 @@ namespace ZeroLevel } catch (Exception ex) { - Log.SystemFatal(ex, "[Bootstrap] The service start in interactive mode was faulted with error"); + Log.Fatal(ex, "[Bootstrap] The service start in interactive mode was faulted with error"); } } else @@ -149,7 +154,7 @@ namespace ZeroLevel } catch (Exception ex) { - Log.SystemFatal(ex, "[Bootstrap] The service start was faulted with error"); + Log.Fatal(ex, "[Bootstrap] The service start was faulted with error"); } } } diff --git a/ZeroLevel/Services/Application/ZeroServiceState.cs b/ZeroLevel/Services/Application/ZeroServiceState.cs index 317757c..7281199 100644 --- a/ZeroLevel/Services/Application/ZeroServiceState.cs +++ b/ZeroLevel/Services/Application/ZeroServiceState.cs @@ -6,17 +6,8 @@ namespace ZeroLevel.Services.Applications public enum ZeroServiceState : int { Initialized = 0, - /// - /// Сервис работает - /// Started = 1, - /// - /// Работа сервиса приостановлена - /// Paused = 2, - /// - /// Сервис остановлен (ресурсы освобождены) - /// Stopped = 3 } } diff --git a/ZeroLevel/Services/Collections/FixSizeQueue.cs b/ZeroLevel/Services/Collections/FixSizeQueue.cs index 568946c..013814e 100644 --- a/ZeroLevel/Services/Collections/FixSizeQueue.cs +++ b/ZeroLevel/Services/Collections/FixSizeQueue.cs @@ -3,9 +3,6 @@ using System.Collections.Generic; namespace ZeroLevel.Services.Collections { - /// - /// Очередь фиксированной длины - /// public sealed class FixSizeQueue : IFixSizeQueue { @@ -26,8 +23,7 @@ namespace ZeroLevel.Services.Collections _count = 0; } /// - /// Добавление элемента в очередь, при достижении предела по размеру, - /// перезаписывается самый старый элемент + /// If count is limited when intem adding, oldest item replace with new item /// public void Push(T item) { diff --git a/ZeroLevel/Services/Collections/RoundRobinCollection.cs b/ZeroLevel/Services/Collections/RoundRobinCollection.cs index b51ac57..457236e 100644 --- a/ZeroLevel/Services/Collections/RoundRobinCollection.cs +++ b/ZeroLevel/Services/Collections/RoundRobinCollection.cs @@ -5,6 +5,11 @@ using System.Threading; namespace ZeroLevel.Services.Collections { + /// + /// Collection return new seq every iteration + /// Sample. Original: [1,2,3]. Iteration #1: [1, 2, 3]. Iteration #2: [2, 3, 1]. Iteration #3: [3, 1, 2]. Iteration #4: [1, 2, 3] + /// + /// public sealed class RoundRobinCollection : IDisposable { diff --git a/ZeroLevel/Services/Collections/SparseIterator.cs b/ZeroLevel/Services/Collections/SparseIterator.cs deleted file mode 100644 index b723d41..0000000 --- a/ZeroLevel/Services/Collections/SparseIterator.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace ZeroLevel.Services.Collections -{ - /// - /// Циклический разреженный итератор - /// позволяет выполнять циклический обход массива, с возможностью отмечать элементы - /// которые требуется прпускать при следующих обходах. - /// - public class SparseIterator - { - private readonly T[] _array; - private readonly HashSet _removed = new HashSet(); - private int index = -1; - - public SparseIterator(IEnumerable items) - { - _array = items.ToArray(); - } - /// - /// Текущий элемент последовательности - /// - public T Current - { - get - { - if (index >= 0 && index < _array.Length) - { - return _array[index]; - } - throw new IndexOutOfRangeException(); - } - } - /// - /// Указывает на отсутствие элементов в последовательности или на - /// то что все элементы были отмечены для пропуска - /// - public bool IsEmpty - { - get - { - return _array.Length == 0 || _array.Length == _removed.Count; - } - } - /// - /// Сдвиг на следующий элемент, если достигнут конец последовательности, - /// переключается на первый неотмеченный для пропуска элемент - /// - /// вернет -1 если последовательность пуста, или если не осталось элементов не отмеченных для пропуска - public int MoveNext() - { - do - { - index++; - } while (_removed.Contains(index)); - if (index >= _array.Length) - { - if (IsEmpty) return -1; - index = -1; - do - { - index++; - } while (_removed.Contains(index)); - } - return index; - } - /// - /// Отмечает текущий элемент для пропуска при следующем обходе - /// - /// - public bool Exclude() - { - if (index >= 0) - { - return _removed.Add(index); - } - return false; - } - } -} diff --git a/ZeroLevel/Services/Config/BaseConfiguration.cs b/ZeroLevel/Services/Config/BaseConfiguration.cs index 9e5e811..1c976c1 100644 --- a/ZeroLevel/Services/Config/BaseConfiguration.cs +++ b/ZeroLevel/Services/Config/BaseConfiguration.cs @@ -8,27 +8,27 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel.Services.Config { /// - /// Упрощенная конфигурация, без разделения параметров по секциям + /// Base configuration /// internal sealed class BaseConfiguration : IConfiguration { #region Private members /// - /// Указывает на заморозку конфигурации, все изменения запрещены + /// When true, any changes disallow /// private bool _freezed = false; /// - /// Указывает на перманентную заморозку конфигурации, разморозка запрещена + /// When true, freeze permanent, can't be canceled /// private bool _permanentFreezed = false; private readonly object _freezeLock = new object(); /// - /// Список вида ключ-значение + /// Key-values dictionary /// private readonly ConcurrentDictionary> _keyValues = new ConcurrentDictionary>(); /// - /// Пустой список + /// Empty list /// private static readonly IEnumerable EmptyValuesList = new List(0); @@ -44,10 +44,10 @@ namespace ZeroLevel.Services.Config #region Properties /// - /// Список значений по ключу + /// Get values by key /// - /// Ключ - /// Список значений + /// key + /// Values list public IEnumerable this[string key] { get @@ -62,7 +62,7 @@ namespace ZeroLevel.Services.Config } } /// - /// Список ключей + /// Keys list /// public IEnumerable Keys { @@ -240,10 +240,10 @@ namespace ZeroLevel.Services.Config #endregion /// - /// Добавление ключа и связанного с ним значения + /// Add key-value /// - /// Ключ - /// Значение + /// Key + /// Value public IConfiguration Append(string key, string value) { if (false == _freezed) @@ -258,8 +258,7 @@ namespace ZeroLevel.Services.Config return this; } /// - /// Задает значение в единственном числе, - /// существующее значение будет перезаписано + /// Set unique value for key /// public IConfiguration SetUnique(string key, string value) { @@ -270,15 +269,18 @@ namespace ZeroLevel.Services.Config { _keyValues.TryAdd(key, new List()); } - _keyValues[key].Clear(); + else + { + _keyValues[key].Clear(); + } _keyValues[key].Add(value?.Trim() ?? null); } return this; } /// - /// Очистка связанного с ключом списка значений + /// Clean values binded with key /// - /// Ключ + /// Key public IConfiguration Clear(string key) { if (false == _freezed) @@ -292,7 +294,7 @@ namespace ZeroLevel.Services.Config return this; } /// - /// Очистка конфигурации + /// Configuration drop /// public IConfiguration Clear() { @@ -303,9 +305,9 @@ namespace ZeroLevel.Services.Config return this; } /// - /// Удаление ключа и связанных с ним значений + /// Remove key and binded values /// - /// Ключ + /// Key public IConfiguration Remove(string key) { if (false == _freezed) diff --git a/ZeroLevel/Services/Config/BaseConfigurationSet.cs b/ZeroLevel/Services/Config/BaseConfigurationSet.cs index 9890308..ea22943 100644 --- a/ZeroLevel/Services/Config/BaseConfigurationSet.cs +++ b/ZeroLevel/Services/Config/BaseConfigurationSet.cs @@ -7,14 +7,14 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel.Services.Config { /// - /// Наборы именованых конфигураций (секций) + /// Named configuration sections array /// internal sealed class BaseConfigurationSet : IConfigurationSet { #region Private members /// - /// Список секций + /// Sections /// private readonly ConcurrentDictionary _sections = new ConcurrentDictionary(); diff --git a/ZeroLevel/Services/Config/Configuration.cs b/ZeroLevel/Services/Config/Configuration.cs index 507fc3b..afa421e 100644 --- a/ZeroLevel/Services/Config/Configuration.cs +++ b/ZeroLevel/Services/Config/Configuration.cs @@ -12,7 +12,7 @@ namespace ZeroLevel public static class Configuration { /// - /// Путь к каталогу приложения + /// Application folder path /// public static string BaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly()?.CodeBase)?. diff --git a/ZeroLevel/Services/Config/IConfiguration.cs b/ZeroLevel/Services/Config/IConfiguration.cs index 2fcda9a..60b7e49 100644 --- a/ZeroLevel/Services/Config/IConfiguration.cs +++ b/ZeroLevel/Services/Config/IConfiguration.cs @@ -5,7 +5,7 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel { /// - /// Интерфейс конфигурационных данных + /// Configuration section /// public interface IConfiguration : IEquatable, @@ -13,103 +13,101 @@ namespace ZeroLevel { #region Properties /// - /// Получение списка значений по ключу + /// Get values by key /// IEnumerable this[string key] { get; } /// - /// Перечисление ключей + /// Keys /// IEnumerable Keys { get; } /// - /// Указывает что конфигурация заблокирована на изменения + /// Configuration is locked for change when true /// bool Freezed { get; } #endregion #region Methods /// - /// Получение списка значений параметра по ключу + /// Get values by key /// - /// Имя параметра - /// Список значений + /// Key + /// Values list IEnumerable Items(string key); /// - /// Получение одного(первого) значения параметра по ключу + /// Get first value by key /// string First(string key); /// - /// Получить первое значение в виде объекта типа T + /// Get first value by key with cast to /// T First(string key); /// - /// Получить первое значение или значение по умолчанию + /// Get first or default value by key /// string FirstOrDefault(string name, string defaultValue); /// - /// Получить первое значение в виде объекта типа T или получить значение по умолчанию + /// Get first or default value by key with cast to /// T FirstOrDefault(string name); /// - /// Получить первое значение в виде объекта типа T или получить переданное значение по умолчанию + /// Get first or default value by key with cast to /// T FirstOrDefault(string name, T defaultValue); /// - /// Проверка наличия ключа + /// Check key exists /// bool Contains(string key); /// - /// Проверка наличия одного из ключей + /// Check one of key exists /// bool Contains(params string[] keys); /// - /// Проверка наличия значения по ключу + /// true if exists one or more values by key /// bool ContainsValue(string key, string value); /// - /// Количество значений параметра + /// Count values by key /// int Count(string key); /// - /// Выполняет указанное действие только в случае если в конфигурации есть ключ + /// Do action if key exists, action takes first value /// void DoWithFirst(string key, Action action); /// - /// Выполняет указанное действие только в случае если в конфигурации есть ключ + /// Do action if key exists, action takes first value with cast to /// void DoWithFirst(string key, Action action); #endregion #region Create, Clean, Delete /// - /// Очистка всей секции + /// Clean /// IConfiguration Clear(); /// - /// Очистка значения ключа + /// Clean values by key /// IConfiguration Clear(string key); /// - /// Удаление ключа и значений + /// Remove key and binded values /// IConfiguration Remove(string key); /// - /// Добавление параметра + /// Append key and value /// IConfiguration Append(string key, string value); /// - /// Задает значение в единственном числе, - /// существующее значение будет перезаписано + /// Set key with one value, if any values by key exists, they will be dropped /// IConfiguration SetUnique(string key, string value); /// - /// Запрещает вносить какие-либо изменения в конфигурацию + /// Sets a prohibition on changing /// - /// false - если уже установлен запрет + /// false - prohibition was set already bool Freeze(bool permanent = false); /// - /// Убирает запрет на внесение изменений в конфигурацию + /// Remove a prohibition on changing /// - /// false - если запрет снят bool Unfreeze(); #endregion } diff --git a/ZeroLevel/Services/Config/IConfigurationSet.cs b/ZeroLevel/Services/Config/IConfigurationSet.cs index bc3a36b..4fae6d6 100644 --- a/ZeroLevel/Services/Config/IConfigurationSet.cs +++ b/ZeroLevel/Services/Config/IConfigurationSet.cs @@ -5,7 +5,7 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel { /// - /// Интерфейс набора конфигурационных данных + /// Named configuration sections array /// public interface IConfigurationSet : IEquatable, @@ -13,72 +13,64 @@ namespace ZeroLevel { #region Properties /// - /// Получение конфигурации по умолчанию + /// Default section, always exists /// IConfiguration Default { get; } /// - /// Получение конфигурации по имени + /// Get configuration section by name /// IConfiguration this[string sectionName] { get; } /// - /// Получение имен конфигураций + /// Get configuration section names /// IEnumerable SectionNames { get; } /// - /// Получение всех конфигураций + /// Get all sections /// IEnumerable Sections { get; } /// - /// Указывает, заблокирован или нет набор секций + /// true if changing disallow /// bool SectionsFreezed { get; } #endregion #region Methods /// - /// Создание секции параметров + /// Create section /// - /// Название секции + /// Section name IConfiguration CreateSection(string sectionName); /// - /// Запрос секции данных по имени секции + /// Get configuration section by name /// /// Название секции /// Секция с данными IConfiguration GetSection(string sectionName); /// - /// Проверка наличия секции с указанным именем + /// Check for a section by name /// - /// Название секции - /// true - секция существует + /// Section name bool ContainsSection(string sectionName); - /// - /// Удаление секции + /// Remove section by name /// - /// Название секции - /// false - если секция уже удалена или не существует + /// Section name bool RemoveSection(string sectionName); /// - /// Запрещает вносить какие-либо изменения в существующую конфигурацию во всех секциях - /// а также менять набор секций + /// Sets a prohibition on changing configurations /// - /// false - если уже установлен запрет bool FreezeConfiguration(bool permanent = false); /// - /// Запрещает вносить какие-либо изменения в существующий набор секций + /// Sets a prohibition on changing sections /// - /// false - если уже установлен запрет bool FreezeSections(bool permanent = false); /// - /// Убирает запрет на внесение изменений в существующую конфигурацию во всех секциях - /// а также разрешает менять набор секций + /// Remove a prohibition on changing configurations /// /// false - если запрет снят bool UnfreezeConfiguration(); /// - /// Убирает запрет на внесение изменений в существующий набор секций + /// Sets a prohibition on changing sections /// - /// false - если запрет снят bool UnfreezeSections(); #endregion } diff --git a/ZeroLevel/Services/Config/Implementation/CommandLineReader.cs b/ZeroLevel/Services/Config/Implementation/CommandLineReader.cs index 7b8299b..87ead47 100644 --- a/ZeroLevel/Services/Config/Implementation/CommandLineReader.cs +++ b/ZeroLevel/Services/Config/Implementation/CommandLineReader.cs @@ -40,7 +40,7 @@ namespace ZeroLevel.Services.Config.Implementation } catch (Exception ex) { - throw new InvalidOperationException("Не удалось создать конфигурацию из аргументов командной строки", ex); + throw new InvalidOperationException("Can't read configuration from command line arguments", ex); } } return result; diff --git a/ZeroLevel/Services/Config/Implementation/IniFileReader.cs b/ZeroLevel/Services/Config/Implementation/IniFileReader.cs index cc636cc..e8386ff 100644 --- a/ZeroLevel/Services/Config/Implementation/IniFileReader.cs +++ b/ZeroLevel/Services/Config/Implementation/IniFileReader.cs @@ -15,13 +15,13 @@ namespace ZeroLevel.Services.Config.Implementation internal IniFileReader(string configPath) { if (String.IsNullOrWhiteSpace(configPath)) - throw new ArgumentNullException("configPath", "Не указан путь к конфигурационному файлу"); + throw new ArgumentNullException("configPath", "File path not found"); if (!File.Exists(configPath)) { configPath = Path.Combine(Configuration.BaseDirectory, configPath); if (!File.Exists(configPath)) { - throw new FileNotFoundException("Не существует конфигурационный файл: " + configPath); + throw new FileNotFoundException("File path not exists: " + configPath); } } _iniPath = configPath; diff --git a/ZeroLevel/Services/Config/Implementation/IniFileWriter.cs b/ZeroLevel/Services/Config/Implementation/IniFileWriter.cs index a57c033..9aa32c3 100644 --- a/ZeroLevel/Services/Config/Implementation/IniFileWriter.cs +++ b/ZeroLevel/Services/Config/Implementation/IniFileWriter.cs @@ -3,27 +3,23 @@ namespace ZeroLevel.Services.Config.Implementation { /// - /// Запись конфигурации в ini-файл + /// Write config to ini-file /// public class IniFileWriter : IConfigurationWriter { /// - /// Путь к ini-файлу + /// Config file path /// private readonly string _iniPath; - /// - /// Инициализирует новый экземпляр класса - /// - /// Путь к ini-файлу + public IniFileWriter(string iniPath) { _iniPath = iniPath; } /// - /// Запись простой конфигурации + /// Write config to file /// - /// Конфигурация public void WriteConfiguration(IConfiguration configuration) { using (TextWriter writer = new StreamWriter(_iniPath, false)) @@ -46,9 +42,8 @@ namespace ZeroLevel.Services.Config.Implementation } } /// - /// Запись конфигурации разбитой по секциям + /// Write configuration set to file /// - /// Конфигурация public void WriteConfigurationSet(IConfigurationSet configuration) { using (TextWriter writer = new StreamWriter(_iniPath, false)) diff --git a/ZeroLevel/Services/DOM/Contracts/IMetadataReader.cs b/ZeroLevel/Services/DOM/Contracts/IMetadataReader.cs index 42c2103..b296247 100644 --- a/ZeroLevel/Services/DOM/Contracts/IMetadataReader.cs +++ b/ZeroLevel/Services/DOM/Contracts/IMetadataReader.cs @@ -11,7 +11,7 @@ namespace ZeroLevel.DocumentObjectModel void EnterIdentifier(Identifier identifier); void ReadVersion(int version); - void ReadTimestamp(string timestamp); + void ReadTimestamp(long timestamp); void ReadDateLabel(string datelabel); void LeaveIdentifier(Identifier identifier); @@ -44,9 +44,9 @@ namespace ZeroLevel.DocumentObjectModel void LeaveHeaders(IEnumerable
headers); void LeaveDescriptioveBlock(DescriptiveMetadata metadata); - void EnterAsides(IEnumerable asides); - void ReadAside(AsideContent aside, int order); - void LeaveAsides(IEnumerable asides); + void EnterAsides(IEnumerable asides); + void ReadAside(AttachContent aside, int order); + void LeaveAsides(IEnumerable asides); void EnterAssotiations(IEnumerable assotiations); void ReadAssotiation(Assotiation assotiation, int order); diff --git a/ZeroLevel/Services/DOM/DSL/Contracts/ISpecialTableBuilder.cs b/ZeroLevel/Services/DOM/DSL/Contracts/ISpecialTableBuilder.cs index ae4f5fd..11d8306 100644 --- a/ZeroLevel/Services/DOM/DSL/Contracts/ISpecialTableBuilder.cs +++ b/ZeroLevel/Services/DOM/DSL/Contracts/ISpecialTableBuilder.cs @@ -6,7 +6,7 @@ namespace DOM.DSL.Contracts public interface ISpecialTableBuilder { /// - /// Указывает что ожидается запись тела ячейки таблицы + /// Indicates that a table cell body entry is expected. /// bool WaitCellBody { get; } void WriteToCell(string part); diff --git a/ZeroLevel/Services/DOM/DSL/Model/TFlowRules.cs b/ZeroLevel/Services/DOM/DSL/Model/TFlowRules.cs index 42d828b..ba33fdd 100644 --- a/ZeroLevel/Services/DOM/DSL/Model/TFlowRules.cs +++ b/ZeroLevel/Services/DOM/DSL/Model/TFlowRules.cs @@ -305,13 +305,13 @@ namespace DOM.DSL.Model case "ignore": TablePrefix = TablePostfix = null; break; - case "special": // Использование захардкоженного преобразования таблицы + case "special": // Using a hardcoded table conversion //TablePrefix = TablePostfix = null; ColumnsPrefix = ColumnsPostfix = null; ColumnPrefix = ColumnTemplate = ColumnPostfix = null; RowPrefix = RowPostfix = null; CellPrefix = CellPostfix = null; - // Аргументы: (style, paddings l-t-r-b, maxcellwidth, maxtablewidth) + // Args: (style, paddings l-t-r-b, maxcellwidth, maxtablewidth) UseSpecialTableBuilder = true; SpecialTableBuilder = SpecialTableBuilderFactory.CreateSpecialTableBuilder(special); if (SpecialTableBuilder == null) UseSpecialTableBuilder = false; diff --git a/ZeroLevel/Services/DOM/DSL/Services/SpecialTableBuilderFactory.cs b/ZeroLevel/Services/DOM/DSL/Services/SpecialTableBuilderFactory.cs index 3d008a8..e61b44a 100644 --- a/ZeroLevel/Services/DOM/DSL/Services/SpecialTableBuilderFactory.cs +++ b/ZeroLevel/Services/DOM/DSL/Services/SpecialTableBuilderFactory.cs @@ -17,12 +17,12 @@ namespace DOM.DSL.Services case "plaintext": // (Borders, 1-0-1-0, 0, 96) var options = new TextTableRenderOptions(); - if (args.Length > 1) // Стиль + if (args.Length > 1) // Style { if (Enum.TryParse(args[1], out options.Style) == false) options.Style = TextTableStyle.Borders; } - if (args.Length > 2) // Паддинги + if (args.Length > 2) // Paddings { var paddings = args[2].Split(' '); int buffer; @@ -40,7 +40,7 @@ namespace DOM.DSL.Services } } } - if (args.Length > 3) // Ширина ячейки + if (args.Length > 3) // Cell width { int buffer; if (true == int.TryParse(args[3].Trim(), out buffer)) @@ -48,7 +48,7 @@ namespace DOM.DSL.Services options.MaxCellWidth = buffer; } } - if (args.Length > 4) // Ширина таблицы + if (args.Length > 4) // Table width { int buffer; if (true == int.TryParse(args[4].Trim(), out buffer)) diff --git a/ZeroLevel/Services/DOM/DSL/Services/TContainer.cs b/ZeroLevel/Services/DOM/DSL/Services/TContainer.cs index f9bb8ff..f5e6feb 100644 --- a/ZeroLevel/Services/DOM/DSL/Services/TContainer.cs +++ b/ZeroLevel/Services/DOM/DSL/Services/TContainer.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Security; using System.Text; using System.Threading; +using ZeroLevel; using ZeroLevel.DocumentObjectModel; using ZeroLevel.DocumentObjectModel.Flow; using ZeroLevel.Services.FileSystem; @@ -56,7 +57,7 @@ namespace DOM.DSL.Services } else { - // Добавляются элементы разных типов, в этом случае все элементы приводим к string + // Added elements of different types. All elements casts to string var list = new List(); foreach (var i in _list) list.Add(i.ToString()); _elementType = typeof(string); @@ -170,7 +171,7 @@ namespace DOM.DSL.Services else if (_current is Category) SelectProperty((Category)_current, propertyName, propertyIndex); else if (_current is Header) SelectProperty((Header)_current, propertyName, propertyIndex); else if (_current is Tag) SelectProperty((Tag)_current, propertyName, propertyIndex); - else if (_current is AsideContent) SelectProperty((AsideContent)_current, propertyName, propertyIndex); + else if (_current is AttachContent) SelectProperty((AttachContent)_current, propertyName, propertyIndex); else if (_current is Assotiation) SelectProperty((Assotiation)_current, propertyName, propertyIndex); else if (_current is List
) SelectProperty((List
)_current, propertyName, propertyIndex); else if (_current is Identifier) SelectProperty((Identifier)_current, propertyName, propertyIndex); @@ -255,8 +256,9 @@ namespace DOM.DSL.Services { return (T)Convert.ChangeType(_current, type); } - catch + catch (Exception ex) { + Log.SystemWarning($"[DOM.TContainer] Fault cast current value from type '{_current?.GetType()?.FullName ?? string.Empty}' to type '{type.FullName}'. {ex.ToString()}"); return default(T); } } @@ -273,8 +275,9 @@ namespace DOM.DSL.Services { return Convert.ChangeType(_current, type); } - catch + catch(Exception ex) { + Log.SystemWarning($"[DOM.TContainer] Fault cast current value from type '{_current?.GetType()?.FullName ?? string.Empty}' to type '{type.FullName}'. {ex.ToString()}"); return TypeHelpers.CreateDefaultState(type); } } @@ -1144,7 +1147,7 @@ namespace DOM.DSL.Services } } - private void SelectProperty(AsideContent aside, string property, string propertyIndex) + private void SelectProperty(AttachContent aside, string property, string propertyIndex) { switch (property.Trim().ToLowerInvariant()) { @@ -2596,7 +2599,7 @@ namespace DOM.DSL.Services else if (_current is Category) return ((Category)_current).Title ?? string.Empty; else if (_current is Header) return ((Header)_current).Value ?? string.Empty; else if (_current is Tag) return ((Tag)_current).Name ?? string.Empty; - else if (_current is AsideContent) return ((AsideContent)_current).Caption ?? string.Empty; + else if (_current is AttachContent) return ((AttachContent)_current).Caption ?? string.Empty; else if (_current is Assotiation) return ((Assotiation)_current).Title ?? string.Empty; else if (_current is List
) return string.Join("; ", ((List
)_current).Select(h => h.Name)); else if (_current is Identifier) return string.Empty; @@ -2640,4 +2643,4 @@ namespace DOM.DSL.Services return _current?.ToString() ?? string.Empty; } } -} +} \ No newline at end of file diff --git a/ZeroLevel/Services/DOM/DSL/Services/TRender.cs b/ZeroLevel/Services/DOM/DSL/Services/TRender.cs index 3172752..642da42 100644 --- a/ZeroLevel/Services/DOM/DSL/Services/TRender.cs +++ b/ZeroLevel/Services/DOM/DSL/Services/TRender.cs @@ -43,64 +43,30 @@ namespace DOM.DSL.Services { private readonly Document _document; private readonly TEnvironment _environment; - private readonly DOMRenderElementCounter _counter; - private readonly TRenderOptions _options = new TRenderOptions(); - private readonly TContainerFactory _factory; - private readonly IDictionary _buffer = - new Dictionary(); - private readonly CustomBlocks _blocks = new CustomBlocks(); - - internal TContainerFactory Factory - { - get - { - return _factory; - } - } - - internal IDictionary BufferDictionary - { - get - { - return _buffer; - } - } - - internal DOMRenderElementCounter Counter - { - get - { - return _counter; - } - } - - internal TRenderOptions Options - { - get - { - return _options; - } - } + internal TContainerFactory Factory { get; } + internal IDictionary BufferDictionary { get; } = new Dictionary(); + internal DOMRenderElementCounter Counter { get; } + internal TRenderOptions Options { get; } = new TRenderOptions(); public TRender(Document document, TEnvironment environment) { _document = document; _environment = environment; - _counter = new DOMRenderElementCounter(); - _factory = new TContainerFactory(this); + Counter = new DOMRenderElementCounter(); + Factory = new TContainerFactory(this); } public void Resolve(TToken token, Action handler, bool release = true, TContainer self = null) { - var self_copy = self == null ? null : _factory.Get(self.Current, self.Index); + var self_copy = self == null ? null : Factory.Get(self.Current, self.Index); try { if (token is TTextToken) { - var container = _factory.Get(token.AsTextToken().Text); + var container = Factory.Get(token.AsTextToken().Text); handler(container); - if (release) _factory.Release(container); + if (release) Factory.Release(container); } else if (token is TElementToken) { @@ -108,7 +74,7 @@ namespace DOM.DSL.Services foreach (var c in containers) { handler(c); - if (release) _factory.Release(c); + if (release) Factory.Release(c); } } else if (token is TBlockToken) @@ -117,13 +83,13 @@ namespace DOM.DSL.Services foreach (var c in containers) { handler(c); - if (release) _factory.Release(c); + if (release) Factory.Release(c); } } } finally { - _factory.Release(self_copy); + Factory.Release(self_copy); } } @@ -133,56 +99,56 @@ namespace DOM.DSL.Services switch (token.ElementName.Trim().ToLowerInvariant()) { // External - case "now": container = _factory.Get(DateTime.Now); break; - case "utc": container = _factory.Get(DateTime.Now.ToUniversalTime()); break; - case "guid": container = _factory.Get(Guid.NewGuid()); break; - case "nowutc": container = _factory.Get(DateTime.UtcNow); break; + case "now": container = Factory.Get(DateTime.Now); break; + case "utc": container = Factory.Get(DateTime.Now.ToUniversalTime()); break; + case "guid": container = Factory.Get(Guid.NewGuid()); break; + case "nowutc": container = Factory.Get(DateTime.UtcNow); break; // Document - case "id": container = _factory.Get(_document.Id); break; - case "summary": container = _factory.Get(_document.Summary); break; - case "header": container = _factory.Get(_document.Header); break; - case "categories": container = _factory.Get(_document.Categories); break; + case "id": container = Factory.Get(_document.Id); break; + case "summary": container = Factory.Get(_document.Summary); break; + case "header": container = Factory.Get(_document.Header); break; + case "categories": container = Factory.Get(_document.Categories); break; case "directions": - container = _factory.Get(_document.Categories. + container = Factory.Get(_document.Categories. Select(c => c.DirectionCode).Distinct().ToList()); break; // Descriptive case "desc": - case "descriptive": container = _factory.Get(_document.DescriptiveMetadata); break; - case "author": container = _factory.Get(_document.DescriptiveMetadata.Byline); break; - case "copyright": container = _factory.Get(_document.DescriptiveMetadata.CopyrightNotice); break; - case "created": container = _factory.Get(_document.DescriptiveMetadata.Created); break; - case "lang": container = _factory.Get(_document.DescriptiveMetadata.Language); break; - case "priority": container = _factory.Get(_document.DescriptiveMetadata.Priority); break; - case "source": container = _factory.Get(_document.DescriptiveMetadata.Source); break; - case "publisher": container = _factory.Get(_document.DescriptiveMetadata.Publisher); break; + case "descriptive": container = Factory.Get(_document.DescriptiveMetadata); break; + case "author": container = Factory.Get(_document.DescriptiveMetadata.Byline); break; + case "copyright": container = Factory.Get(_document.DescriptiveMetadata.CopyrightNotice); break; + case "created": container = Factory.Get(_document.DescriptiveMetadata.Created); break; + case "lang": container = Factory.Get(_document.DescriptiveMetadata.Language); break; + case "priority": container = Factory.Get(_document.DescriptiveMetadata.Priority); break; + case "source": container = Factory.Get(_document.DescriptiveMetadata.Source); break; + case "publisher": container = Factory.Get(_document.DescriptiveMetadata.Publisher); break; case "meta": - case "headers": container = _factory.Get(_document.DescriptiveMetadata.Headers); break; + case "headers": container = Factory.Get(_document.DescriptiveMetadata.Headers); break; // Identifier - case "identifier": container = _factory.Get(_document.Identifier); break; - case "timestamp": container = _factory.Get(_document.Identifier.Timestamp); break; - case "datelabel": container = _factory.Get(_document.Identifier.DateLabel); break; - case "version": container = _factory.Get(_document.Identifier.Version); break; + case "identifier": container = Factory.Get(_document.Identifier); break; + case "timestamp": container = Factory.Get(_document.Identifier.Timestamp); break; + case "datelabel": container = Factory.Get(_document.Identifier.DateLabel); break; + case "version": container = Factory.Get(_document.Identifier.Version); break; // Tags - case "tags": container = _factory.Get(_document.TagMetadata); break; - case "keywords": container = _factory.Get(_document.TagMetadata.Keywords); break; - case "companies": container = _factory.Get(_document.TagMetadata.Companies); break; - case "persons": container = _factory.Get(_document.TagMetadata.Persons); break; - case "places": container = _factory.Get(_document.TagMetadata.Places); break; + case "tags": container = Factory.Get(_document.TagMetadata); break; + case "keywords": container = Factory.Get(_document.TagMetadata.Keywords); break; + case "companies": container = Factory.Get(_document.TagMetadata.Companies); break; + case "persons": container = Factory.Get(_document.TagMetadata.Persons); break; + case "places": container = Factory.Get(_document.TagMetadata.Places); break; - case "var": container = _factory.Get(_environment.CustomVariables); break; - case "buf": container = _factory.Get(_buffer); break; - case "env": container = _factory.Get(_environment); break; - case "counter": container = _factory.Get(_counter); break; - case "self": container = _factory.Get(self.Current, self.Index); break; - case "content": container = _factory.Get(new TContentElement(_document)); break; - case "aside": container = _factory.Get(_document.Aside); break; - case "assotiations": container = _factory.Get(_document.Assotiations); break; - case "null": container = _factory.Get(null); break; - case "empty": container = _factory.Get(string.Empty); break; + case "var": container = Factory.Get(_environment.CustomVariables); break; + case "buf": container = Factory.Get(BufferDictionary); break; + case "env": container = Factory.Get(_environment); break; + case "counter": container = Factory.Get(Counter); break; + case "self": container = Factory.Get(self.Current, self.Index); break; + case "content": container = Factory.Get(new TContentElement(_document)); break; + case "aside": container = Factory.Get(_document.Attachments); break; + case "assotiations": container = Factory.Get(_document.Assotiations); break; + case "null": container = Factory.Get(null); break; + case "empty": container = Factory.Get(string.Empty); break; // Blocks case "build": @@ -191,15 +157,15 @@ namespace DOM.DSL.Services { var block = new TBlockToken(_blocks.Get(token.NextToken.AsPropertyToken().PropertyName)); var result = ResolveBlockToken(block, self); - container = _factory.Get(result.Where(c => c.Current != null).Select(c => c.Current).ToList()); + container = Factory.Get(result.Where(c => c.Current != null).Select(c => c.Current).ToList()); foreach (var c in result) - _factory.Release(c); + Factory.Release(c); } break; } } - if (container == null) container = _factory.Get(null); + if (container == null) container = Factory.Get(null); if (token.NextToken is TPropertyToken) { @@ -286,13 +252,13 @@ namespace DOM.DSL.Services List result; if (success) { - var ls = self_parent == null ? null : _factory.Get(self_parent.Current, self_parent.Index); + var ls = self_parent == null ? null : Factory.Get(self_parent.Current, self_parent.Index); result = ResolveSimpleBlockToken(blockToken, ls); - _factory.Release(ls); + Factory.Release(ls); } else { - result = new List { _factory.Get(null) }; + result = new List { Factory.Get(null) }; } return result; } @@ -308,12 +274,12 @@ namespace DOM.DSL.Services int index = 0; foreach (var t in (IEnumerable)self_container.Current) { - var self = _factory.Get(t, index); + var self = Factory.Get(t, index); foreach (var bt in blockToken.Body) { Resolve(bt, c => list.Add(c), false, self); } - _factory.Release(self); + Factory.Release(self); index++; } } @@ -325,7 +291,7 @@ namespace DOM.DSL.Services } } } - _factory.Release(self_container); + Factory.Release(self_container); return list; } } @@ -366,12 +332,12 @@ namespace DOM.DSL.Services } special = string.Join(",", args.Select(a => a.ToString())); foreach (var a in args) - _factory.Release(a); + Factory.Release(a); } rules.UpdateRule(elementName, functionName, rule_token, special); } } - return _factory.Get(DocumentContentReader.ReadAs(_document, new TContentToStringConverter(this, rules))); + return Factory.Get(DocumentContentReader.ReadAs(_document, new TContentToStringConverter(this, rules))); } private void ApplyRenderCommand(TSystemToken token) @@ -396,13 +362,13 @@ namespace DOM.DSL.Services switch (args[0].ToString().Trim().ToLowerInvariant()) { case "xml": - _options.ValidateAsXml = true; + Options.ValidateAsXml = true; break; case "html": - _options.ValidateAsHtml = true; + Options.ValidateAsHtml = true; break; case "json": - _options.ValidateAsJson = true; + Options.ValidateAsJson = true; break; } } @@ -414,22 +380,24 @@ namespace DOM.DSL.Services int width; if (int.TryParse(args[0].ToString(), out width)) { - _options.MaxStringWidth = width; + Options.MaxStringWidth = width; } else { - _options.MaxStringWidth = -1; + Options.MaxStringWidth = -1; } } else { - _options.MaxStringWidth = -1; + Options.MaxStringWidth = -1; } } break; } foreach (var a in args) - _factory.Release(a); + { + Factory.Release(a); + } } } } diff --git a/ZeroLevel/Services/DOM/DSL/TEngine.cs b/ZeroLevel/Services/DOM/DSL/TEngine.cs index fa76c46..1b3c249 100644 --- a/ZeroLevel/Services/DOM/DSL/TEngine.cs +++ b/ZeroLevel/Services/DOM/DSL/TEngine.cs @@ -28,7 +28,7 @@ namespace DOM.DSL } catch (Exception ex) { - Log.SystemError(ex, "Fault parse template '{0}' to token list", template); + Log.SystemError(ex, $"Fault parse template '{template}' to token list"); } } return Enumerable.Empty(); @@ -69,7 +69,7 @@ namespace DOM.DSL } catch (Exception ex) { - Log.Debug("Fault transform document '{0} by token list'. {1}", document.Id, ex); + Log.Debug($"Fault transform document '{document.Id} by token list'. {ex.ToString()}"); if (ignore_fault == false) { throw ex; diff --git a/ZeroLevel/Services/DOM/DSL/Tokens/TElementToken.cs b/ZeroLevel/Services/DOM/DSL/Tokens/TElementToken.cs index 7cb580c..d538a67 100644 --- a/ZeroLevel/Services/DOM/DSL/Tokens/TElementToken.cs +++ b/ZeroLevel/Services/DOM/DSL/Tokens/TElementToken.cs @@ -1,7 +1,7 @@ namespace DOM.DSL.Tokens { /// - /// Токен ссылающийся на элемент документа + /// Token referring to the document element /// public class TElementToken : TToken @@ -11,7 +11,7 @@ ///
public string ElementName; /// - /// Опционально, при наличии свойств и/или функций для текущего элемента + /// Optionally, next token /// public TToken NextToken; diff --git a/ZeroLevel/Services/DOM/DSL/Tokens/TTextToken.cs b/ZeroLevel/Services/DOM/DSL/Tokens/TTextToken.cs index eb6c05c..889bfa9 100644 --- a/ZeroLevel/Services/DOM/DSL/Tokens/TTextToken.cs +++ b/ZeroLevel/Services/DOM/DSL/Tokens/TTextToken.cs @@ -1,13 +1,13 @@ namespace DOM.DSL.Tokens { /// - /// Текстовый токен + /// Text token /// public class TTextToken : TToken { /// - /// Текст в шаблоне, переносимый в результат без обработки + /// Constant text /// public string Text; diff --git a/ZeroLevel/Services/DOM/DSL/Tokens/TToken.cs b/ZeroLevel/Services/DOM/DSL/Tokens/TToken.cs index 64b97ee..b9bf4ef 100644 --- a/ZeroLevel/Services/DOM/DSL/Tokens/TToken.cs +++ b/ZeroLevel/Services/DOM/DSL/Tokens/TToken.cs @@ -3,13 +3,13 @@ namespace DOM.DSL.Tokens { /// - /// Абстрактная единица шаблона + /// Abstract token /// public abstract class TToken : TCloneable { public abstract TToken Clone(); /// - /// Копия с установкой NextToken в null, для предотвращения циклических расчетов + /// Copying token with set NextToken to null, to break cycle /// /// public abstract TToken CloneLocal(); diff --git a/ZeroLevel/Services/DOM/Model/Agency.cs b/ZeroLevel/Services/DOM/Model/Agency.cs index 0fcf263..5f8d379 100644 --- a/ZeroLevel/Services/DOM/Model/Agency.cs +++ b/ZeroLevel/Services/DOM/Model/Agency.cs @@ -5,15 +5,15 @@ namespace ZeroLevel.DocumentObjectModel public class Agency : IBinarySerializable { /// - /// Название источника + /// Agency name /// public string Title; /// - /// Ссылка на источник + /// Agency website /// public string Url; /// - /// Описание источника + /// Description /// public string Description; diff --git a/ZeroLevel/Services/DOM/Model/Assotiation.cs b/ZeroLevel/Services/DOM/Model/Assotiation.cs index 03a5cbb..9dace00 100644 --- a/ZeroLevel/Services/DOM/Model/Assotiation.cs +++ b/ZeroLevel/Services/DOM/Model/Assotiation.cs @@ -8,19 +8,19 @@ namespace ZeroLevel.DocumentObjectModel { #region Fields /// - /// Заголовок + /// Title /// public string Title; /// - /// Описание (например, что было изменено по сравнению с прошлой версией) + /// Description /// public string Description; /// - /// Ссылка на связанный документ + /// Binded document reference /// public Guid DocumentId; /// - /// Тип связи + /// Relation type /// public AssotiationRelation Relation; #endregion diff --git a/ZeroLevel/Services/DOM/Model/AssotiationRelation.cs b/ZeroLevel/Services/DOM/Model/AssotiationRelation.cs index 066b6ff..c05d06a 100644 --- a/ZeroLevel/Services/DOM/Model/AssotiationRelation.cs +++ b/ZeroLevel/Services/DOM/Model/AssotiationRelation.cs @@ -5,23 +5,23 @@ namespace ZeroLevel.DocumentObjectModel public enum AssotiationRelation : Int32 { /// - /// Тип отношения не определен + /// Relation type not defined /// Uncknown = 0, /// - /// Упоминается + /// Mentioned /// Mentions = 1, /// - /// Рассказывается о + /// It tells about /// About = 2, /// - /// Обновление предыдущей версии + /// Previous version update /// UpdateOf = 3, /// - /// Основано на + /// Based on /// BasedOn = 4 } diff --git a/ZeroLevel/Services/DOM/Model/AsideContent.cs b/ZeroLevel/Services/DOM/Model/AttachContent.cs similarity index 72% rename from ZeroLevel/Services/DOM/Model/AsideContent.cs rename to ZeroLevel/Services/DOM/Model/AttachContent.cs index 87910b5..e31caf2 100644 --- a/ZeroLevel/Services/DOM/Model/AsideContent.cs +++ b/ZeroLevel/Services/DOM/Model/AttachContent.cs @@ -3,33 +3,33 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel.DocumentObjectModel { - public sealed class AsideContent + public sealed class AttachContent : IBinarySerializable { /// - /// Идентификатор + /// ID /// public string Identity; /// - /// Название содержимого + /// Title /// public string Caption; /// - /// Описание (опционально) + /// Description (optional) /// public string Summary; /// - /// Тип содержимого + /// Content type /// public ContentType ContentType; /// - /// Содержимое в бинарном представлении + /// Binary content /// public byte[] Payload; - public AsideContent() { } - public AsideContent(IBinaryReader reader) { Deserialize(reader); } - public AsideContent(string identity, string caption, string description) + public AttachContent() { } + public AttachContent(IBinaryReader reader) { Deserialize(reader); } + public AttachContent(string identity, string caption, string description) { Identity = identity; Summary = description; Caption = caption; } #region IBinarySerializable diff --git a/ZeroLevel/Services/DOM/Model/Category.cs b/ZeroLevel/Services/DOM/Model/Category.cs index a790eb0..4eb9b0d 100644 --- a/ZeroLevel/Services/DOM/Model/Category.cs +++ b/ZeroLevel/Services/DOM/Model/Category.cs @@ -43,28 +43,27 @@ namespace ZeroLevel.DocumentObjectModel #region Fields /// - /// Название + /// Title /// public string Title { get; set; } /// - /// Описание + /// Description /// public string Description { get; set; } /// - /// Код категории + /// Category code /// public string Code { get; set; } /// - /// Код направления + /// Direction code /// public string DirectionCode { get; set; } /// - /// Указывает на принадлежность категории внутренней части системы - /// Категория не предназначенна для публичного доступа + /// Is instrnal category /// public bool IsSystem { get; set; } diff --git a/ZeroLevel/Services/DOM/Model/DescriptiveMetadata.cs b/ZeroLevel/Services/DOM/Model/DescriptiveMetadata.cs index a07cf71..9b453e7 100644 --- a/ZeroLevel/Services/DOM/Model/DescriptiveMetadata.cs +++ b/ZeroLevel/Services/DOM/Model/DescriptiveMetadata.cs @@ -23,39 +23,39 @@ namespace ZeroLevel.DocumentObjectModel #region Fields /// - /// Авторы (подпись) + /// Authors /// public string Byline; /// - /// Копирайт + /// Copyright /// public string CopyrightNotice; /// - /// Дата создания + /// Creation date /// public DateTime Created; /// - /// Основной язык + /// Main language /// public string Language; /// - /// Важность + /// Priority /// public Priority Priority; /// - /// Источник документа (например, информационное агентство) + /// Document source /// public Agency Source; /// - /// Издатель (Агентство) + /// Document publisher /// public Agency Publisher; /// - /// Ссылка на оригинальную новость, если текущая создана на ее основе + /// Reference to original document /// public Tag Original; /// - /// Опциональные заголовки + /// Headers (optional) /// public List
Headers; #endregion diff --git a/ZeroLevel/Services/DOM/Model/Document.cs b/ZeroLevel/Services/DOM/Model/Document.cs index 4c22f08..0deb6e3 100644 --- a/ZeroLevel/Services/DOM/Model/Document.cs +++ b/ZeroLevel/Services/DOM/Model/Document.cs @@ -35,49 +35,49 @@ namespace ZeroLevel.DocumentObjectModel Content = new FlowContent(); TagMetadata = new TagMetadata(); DescriptiveMetadata = new DescriptiveMetadata(); - Aside = new List(); + Attachments = new List(); Assotiations = new List(); Categories = new List(); } /// - /// Идентификатор документа + /// ID /// public Guid Id; /// - /// Краткое описание, лид + /// Short description /// public string Summary; /// - /// Заголовок + /// Title /// public string Header; /// - /// Дополнительные идентификаторы + /// Identification block /// public Identifier Identifier; /// - /// Содержимое документа + /// Content /// public FlowContent Content; /// - /// Теги + /// Tags /// public TagMetadata TagMetadata; /// - /// Метаданные документа + /// Metadata /// public DescriptiveMetadata DescriptiveMetadata; /// - /// Вложенные документы + /// Attachments /// - public List Aside; + public List Attachments; /// - /// Связанные документы + /// Binded documents /// public List Assotiations; /// - /// Категории + /// Categories /// public List Categories; @@ -94,7 +94,7 @@ namespace ZeroLevel.DocumentObjectModel writer.Write(this.TagMetadata); writer.Write(this.DescriptiveMetadata); - writer.WriteCollection(this.Aside); + writer.WriteCollection(this.Attachments); writer.WriteCollection(this.Assotiations); writer.WriteCollection(this.Categories); } @@ -110,7 +110,7 @@ namespace ZeroLevel.DocumentObjectModel this.TagMetadata = reader.Read(); this.DescriptiveMetadata = reader.Read(); - this.Aside = reader.ReadCollection(); + this.Attachments = reader.ReadCollection(); this.Assotiations = reader.ReadCollection(); this.Categories = reader.ReadCollection(); } diff --git a/ZeroLevel/Services/DOM/Model/Flow/Audio.cs b/ZeroLevel/Services/DOM/Model/Flow/Audio.cs index 672179e..f23c7a1 100644 --- a/ZeroLevel/Services/DOM/Model/Flow/Audio.cs +++ b/ZeroLevel/Services/DOM/Model/Flow/Audio.cs @@ -8,11 +8,11 @@ namespace ZeroLevel.DocumentObjectModel.Flow { public SourceType Source { get; set; } /// - /// Название + /// Title /// public string Title; /// - /// Ссылка или идентификатор вложения + /// Link or Attachment ID /// public string Identifier; diff --git a/ZeroLevel/Services/DOM/Model/Flow/FlowAlign.cs b/ZeroLevel/Services/DOM/Model/Flow/FlowAlign.cs index a9ddc1b..9d9dea1 100644 --- a/ZeroLevel/Services/DOM/Model/Flow/FlowAlign.cs +++ b/ZeroLevel/Services/DOM/Model/Flow/FlowAlign.cs @@ -3,24 +3,24 @@ namespace ZeroLevel.DocumentObjectModel.Flow { /// - /// Смещение содержимого в потоке + /// Content Offset in flow /// public enum FlowAlign : Int32 { /// - /// Без смещения + /// None /// None = 0, /// - /// Смещение к левой части, допускает продолжение потока справа + /// Flow: left /// Left = 1, /// - /// Смещение к правой части, допускает продолжение потока слева + /// Flow: right /// Right = 2, /// - /// Выравнивание по центру + /// Block /// Center = 3 } diff --git a/ZeroLevel/Services/DOM/Model/Flow/FormContent.cs b/ZeroLevel/Services/DOM/Model/Flow/FormContent.cs index 0757455..96e4698 100644 --- a/ZeroLevel/Services/DOM/Model/Flow/FormContent.cs +++ b/ZeroLevel/Services/DOM/Model/Flow/FormContent.cs @@ -4,7 +4,7 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel.DocumentObjectModel.Flow { /// - /// Отображение вложенного документа или содержимого по внешней ссылке + /// Attached document or content by external link /// public sealed class FormContent : ContentElement { diff --git a/ZeroLevel/Services/DOM/Model/Flow/Image.cs b/ZeroLevel/Services/DOM/Model/Flow/Image.cs index c7d4bbd..c6e2377 100644 --- a/ZeroLevel/Services/DOM/Model/Flow/Image.cs +++ b/ZeroLevel/Services/DOM/Model/Flow/Image.cs @@ -9,11 +9,11 @@ namespace ZeroLevel.DocumentObjectModel.Flow public SourceType Source { get; set; } public FlowAlign Align = FlowAlign.None; /// - /// Название + /// Title /// public string Title; /// - /// Ссылка или идентификатор вложения + /// Link or Attachment ID /// public string Identifier; diff --git a/ZeroLevel/Services/DOM/Model/Flow/Paragraph.cs b/ZeroLevel/Services/DOM/Model/Flow/Paragraph.cs index 7f1b8a7..0725fb0 100644 --- a/ZeroLevel/Services/DOM/Model/Flow/Paragraph.cs +++ b/ZeroLevel/Services/DOM/Model/Flow/Paragraph.cs @@ -5,7 +5,7 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel.DocumentObjectModel.Flow { /// - /// Параграф + /// Paragraph /// public class Paragraph : ContentElement diff --git a/ZeroLevel/Services/DOM/Model/Flow/Section.cs b/ZeroLevel/Services/DOM/Model/Flow/Section.cs index 40f889e..1b7b412 100644 --- a/ZeroLevel/Services/DOM/Model/Flow/Section.cs +++ b/ZeroLevel/Services/DOM/Model/Flow/Section.cs @@ -5,7 +5,7 @@ using ZeroLevel.Services.Serialization; namespace ZeroLevel.DocumentObjectModel.Flow { /// - /// Логически завершенный информационный блок + /// Document block /// public class Section : ContentElement diff --git a/ZeroLevel/Services/DOM/Model/Flow/Video.cs b/ZeroLevel/Services/DOM/Model/Flow/Video.cs index bd198be..fa1c9ca 100644 --- a/ZeroLevel/Services/DOM/Model/Flow/Video.cs +++ b/ZeroLevel/Services/DOM/Model/Flow/Video.cs @@ -8,11 +8,11 @@ namespace ZeroLevel.DocumentObjectModel.Flow { public SourceType Source { get; set; } /// - /// Название + /// Title /// public string Title; /// - /// Ссылка или идентификатор вложения + /// Link or Attachment ID /// public string Identifier; diff --git a/ZeroLevel/Services/DOM/Model/FlowContent.cs b/ZeroLevel/Services/DOM/Model/FlowContent.cs index 5c3e412..8ac0a97 100644 --- a/ZeroLevel/Services/DOM/Model/FlowContent.cs +++ b/ZeroLevel/Services/DOM/Model/FlowContent.cs @@ -7,9 +7,6 @@ namespace ZeroLevel.DocumentObjectModel public class FlowContent : ContentElement { - /// - /// Содержимое - /// public List
Sections = new List
(); public FlowContent() : diff --git a/ZeroLevel/Services/DOM/Model/Header.cs b/ZeroLevel/Services/DOM/Model/Header.cs index 3b8b2ec..5f3988f 100644 --- a/ZeroLevel/Services/DOM/Model/Header.cs +++ b/ZeroLevel/Services/DOM/Model/Header.cs @@ -24,21 +24,9 @@ namespace ZeroLevel.DocumentObjectModel #endregion #region Fields - /// - /// Название - /// public string Name; - /// - /// Значение - /// public string Value; - /// - /// Тип - /// public string Type; - /// - /// Дополнительная информация - /// public string Tag; #endregion diff --git a/ZeroLevel/Services/DOM/Model/Identifier.cs b/ZeroLevel/Services/DOM/Model/Identifier.cs index 4ad20d8..b8c81e2 100644 --- a/ZeroLevel/Services/DOM/Model/Identifier.cs +++ b/ZeroLevel/Services/DOM/Model/Identifier.cs @@ -10,17 +10,15 @@ namespace ZeroLevel.DocumentObjectModel #region Fields /// - /// Версия документа + /// Version /// public int Version; /// - /// Идентификатор по дате выхода, дает возможность идентифицировать - /// последнюю полученную по запросу новость, для последующих запросов - /// обновлений + /// Timestamp ID /// - public string Timestamp; + public long Timestamp; /// - /// Идентификатор по дате выхода с масштабированием до дня (20161024) + /// Label with day accurcy /// public string DateLabel; #endregion @@ -29,14 +27,14 @@ namespace ZeroLevel.DocumentObjectModel public void Serialize(IBinaryWriter writer) { writer.WriteInt32(this.Version); - writer.WriteString(this.Timestamp); + writer.WriteLong(this.Timestamp); writer.WriteString(this.DateLabel); } public void Deserialize(IBinaryReader reader) { this.Version = reader.ReadInt32(); - this.Timestamp = reader.ReadString(); + this.Timestamp = reader.ReadLong(); this.DateLabel = reader.ReadString(); } #endregion diff --git a/ZeroLevel/Services/DOM/Model/Priority.cs b/ZeroLevel/Services/DOM/Model/Priority.cs index 451d1a2..c374912 100644 --- a/ZeroLevel/Services/DOM/Model/Priority.cs +++ b/ZeroLevel/Services/DOM/Model/Priority.cs @@ -3,21 +3,13 @@ using System.ComponentModel; namespace ZeroLevel.DocumentObjectModel { - public enum Priority : Int32 + public enum Priority + : Int32 { - /// - /// Обычный - /// [Description("Normal")] Normal = 0, - /// - /// Срочный - /// [Description("Express")] Express = 1, - /// - /// Молния - /// [Description("Flash")] Flash = 2 } diff --git a/ZeroLevel/Services/DOM/Model/Tag.cs b/ZeroLevel/Services/DOM/Model/Tag.cs index be59820..eba21d3 100644 --- a/ZeroLevel/Services/DOM/Model/Tag.cs +++ b/ZeroLevel/Services/DOM/Model/Tag.cs @@ -6,13 +6,7 @@ namespace ZeroLevel.DocumentObjectModel IBinarySerializable { #region Fields - /// - /// Название - /// public string Name; - /// - /// Значение - /// public string Value; #endregion diff --git a/ZeroLevel/Services/DOM/Model/TagMetadata.cs b/ZeroLevel/Services/DOM/Model/TagMetadata.cs index 3910679..139f889 100644 --- a/ZeroLevel/Services/DOM/Model/TagMetadata.cs +++ b/ZeroLevel/Services/DOM/Model/TagMetadata.cs @@ -19,19 +19,18 @@ namespace ZeroLevel.DocumentObjectModel #region Fields /// - /// Упоминаемые места + /// Placec (city, country, etc) /// public List Places; /// - /// Упоминаемые компании + /// Companies /// public List Companies; /// - /// Упоминаемые персоны + /// Persons /// public List Persons; - /// - /// Ключевые слова + /// Keywords /// public List Keywords; #endregion diff --git a/ZeroLevel/Services/DOM/Services/ContentBuilder.cs b/ZeroLevel/Services/DOM/Services/ContentBuilder.cs index 65ef152..52031ac 100644 --- a/ZeroLevel/Services/DOM/Services/ContentBuilder.cs +++ b/ZeroLevel/Services/DOM/Services/ContentBuilder.cs @@ -236,14 +236,12 @@ namespace DOM.Services private void RaiseIncorrectTypeException(ContentElementType received, ContentElementType expected) { - throw new InvalidCastException(string.Format("Type {0} received instead of {1}", - received.ToString(), expected.ToString())); + throw new InvalidCastException($"Type {received} received instead of {expected}"); } private void RaiseIncorrectContainerType(ContentElementType containerType, ContentElementType elementType) { - throw new Exception(string.Format("Type {0} can not be written to a container of type {1}", - elementType.ToString(), containerType.ToString())); + throw new Exception($"Type {elementType} can not be written to a container of type {containerType}"); } private void ReduceContainers() @@ -278,7 +276,7 @@ namespace DOM.Services LeaveRow(); break; default: - throw new Exception(string.Format("Uncknown container type {0}", current.Type.ToString())); + throw new Exception($"Uncknown container type {current.Type}"); } } } @@ -463,7 +461,7 @@ namespace DOM.Services WriteElement(column); } - public void WriteText(ZeroLevel.DocumentObjectModel.Flow.Text text) + public void WriteText(Text text) { if (text == null) { @@ -473,15 +471,15 @@ namespace DOM.Services } public void WriteText(string text) { - WriteElement(new ZeroLevel.DocumentObjectModel.Flow.Text(text)); + WriteElement(new Text(text)); } public void WriteText(string text, TextStyle style) { - WriteElement(new ZeroLevel.DocumentObjectModel.Flow.Text(text) { Style = style }); + WriteElement(new Text(text) { Style = style }); } public void WriteHeader(string text) { - WriteElement(new ZeroLevel.DocumentObjectModel.Flow.Text(text) { Style = new TextStyle { Size = TextSize.MediumHeader, Formatting = TextFormatting.None } }); + WriteElement(new Text(text) { Style = new TextStyle { Size = TextSize.MediumHeader, Formatting = TextFormatting.None } }); } public void WriteQuote(Quote quote) { diff --git a/ZeroLevel/Services/DOM/Services/DocumentContentReader.cs b/ZeroLevel/Services/DOM/Services/DocumentContentReader.cs index 91161fa..cc2005d 100644 --- a/ZeroLevel/Services/DOM/Services/DocumentContentReader.cs +++ b/ZeroLevel/Services/DOM/Services/DocumentContentReader.cs @@ -192,12 +192,12 @@ namespace DOM.Services reader.LeaveHeaders(doc.DescriptiveMetadata.Headers); reader.LeaveDescriptioveBlock(doc.DescriptiveMetadata); - reader.EnterAsides(doc.Aside); - for (int i = 0; i < doc.Aside.Count; i++) + reader.EnterAsides(doc.Attachments); + for (int i = 0; i < doc.Attachments.Count; i++) { - reader.ReadAside(doc.Aside[i], i); + reader.ReadAside(doc.Attachments[i], i); } - reader.LeaveAsides(doc.Aside); + reader.LeaveAsides(doc.Attachments); reader.EnterAssotiations(doc.Assotiations); for (int i = 0; i < doc.Assotiations.Count; i++) diff --git a/ZeroLevel/Services/DependencyInjection/Container.cs b/ZeroLevel/Services/DependencyInjection/Container.cs index 8cb8316..17516f6 100644 --- a/ZeroLevel/Services/DependencyInjection/Container.cs +++ b/ZeroLevel/Services/DependencyInjection/Container.cs @@ -84,14 +84,14 @@ namespace ZeroLevel.Patterns.DependencyInjection private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim(); /// - /// Маппинг контракт - резрешения + /// Map - contract - dependency resolving /// private readonly Dictionary> _resolvingMap = new Dictionary>(); private readonly object _constructorCacheeLocker = new object(); /// - /// Кэш данных о контрукторах типа + /// Types constructors cache /// private readonly Dictionary> _constructorCachee = new Dictionary>(); @@ -99,11 +99,11 @@ namespace ZeroLevel.Patterns.DependencyInjection #region Private /// - /// Создание экземпляра объекта по указанному разрешению зависимости + /// Creating an instance of an object at the specified dependency resolution /// - /// Метаданные разрешения зависимости - /// Аргументы конструктора - /// Экземпляр объекта + /// Dependency resolving metadata + /// Ctor args + /// Instance private object MakeResolving(ResolveTypeInfo resolveType, object[] args, bool compose = true) { Type instanceType = resolveType.ImplementationType; @@ -127,12 +127,12 @@ namespace ZeroLevel.Patterns.DependencyInjection return sessionInstance; } /// - /// Создание экземпляра объекта по указанному разрешению зависимости, для обобщенного типа контракта + /// Creating an instance of the object at the specified dependency resolution, for a generic type of contract /// - /// Метаданные разрешения зависимости - /// Обобщенный тип контракта - /// Аргументы конструктора - /// Экземпляр объекта + /// Dependency resolving metadata + /// Generic contract + /// Ctor args + /// Instance private object MakeGenericResolving(ResolveTypeInfo resolveType, Type genericType, object[] args, bool compose = true) { if (null == resolveType.GenericCachee) @@ -171,31 +171,31 @@ namespace ZeroLevel.Patterns.DependencyInjection return sessionInstance; } /// - /// Сбор свойств типа помеченных аттрибутом разрешения зависимости + /// Collecting properties of the type marked with attribute dependency resolution /// - /// Тип - /// Список свойств отмеченных аттрибутом Resolve + /// Type + /// List of properties marked with "Resolve" attribute private static IEnumerable CollectResolvingProperties(Type type) { return type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy). Where(p => p.GetCustomAttribute() != null); } /// - /// Сбор полей типа помеченных аттрибутом разрешения зависимости + /// Collecting fields of type marked with an attribute of dependency resolution /// - /// Тип - /// Список полей отмеченных аттрибутом Resolve + /// Type + /// List of properties marked with "Resolve" attribute private static IEnumerable CollectResolvingFields(Type type) { return type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy). Where(p => p.GetCustomAttribute() != null); } /// - /// Поиск разрешения зависимости + /// Search for dependency resolution /// - /// Тип контракта - /// Имя разрешения зависимости - /// Переопределенный тип контракта + /// Contract + /// Dependency name + /// Redefined contract type /// private ResolveTypeInfo FindResolving(Type type, string resolveName, Type contractType) { @@ -227,15 +227,14 @@ namespace ZeroLevel.Patterns.DependencyInjection _rwLock.ExitReadLock(); } } - throw new KeyNotFoundException(string.Format("Не удалось разрешить зависимость для типа {0} по ключу '{1}'", - type.FullName, resolveName)); + throw new KeyNotFoundException($"Can't resolve dependency by type '{type.FullName}' and dependency name '{resolveName}'"); } /// - /// Разрешение зависимости по аттрибуту Resolve + /// Resolving dependency on attribute "Resolve /// - /// Тип контракта - /// Аттрибут - /// Экземпляр объекта + /// Contract + /// Resolve attribute + /// Instance private object MakeInstanceBy(Type type, ResolveAttribute resolveAttribute) { var is_generic = false; @@ -256,16 +255,14 @@ namespace ZeroLevel.Patterns.DependencyInjection } catch (Exception ex) { - throw new Exception( - string.Format("Не удалось создать экземпляр типа {0} для разрешения зависимости типа {1} по ключу {2}", - type.FullName, type.FullName, resolveAttribute?.ResolveName), ex); + throw new Exception($"Can't create type '{type.FullName}' instance for contract type {type.FullName}. Dependency key: '{resolveAttribute?.ResolveName}'", ex); } } /// - /// Сбор интерфейсов и абстрактных классов от которых унаследован тип + /// Collection of interfaces and abstract classes from which the type is inherited /// - /// Тип - /// Список интерфейсов и абстрактных классов + /// Type + /// List of interfaces and abstract classes private static IEnumerable GetInterfacesAndAbstracts(Type sourceType) { var interfaces = sourceType.GetInterfaces().ToList(); @@ -279,10 +276,10 @@ namespace ZeroLevel.Patterns.DependencyInjection return interfaces; } /// - /// Получение списка метаданных по конструкторам типа + /// Getting a list of metadata by type constructors /// - /// Тип - /// Метаданные о конструкторах типа + /// Type + /// Metadata type constructors private IEnumerable GetConstructors(Type type) { lock (_constructorCacheeLocker) @@ -301,11 +298,11 @@ namespace ZeroLevel.Patterns.DependencyInjection return _constructorCachee[type]; } /// - /// Создание экземпляра объекта, в том числе с непубличными конструкторами + /// Creating an instance of an object, including with non-public constructors /// - /// Тип - /// Аргументы конструктора - /// Экземпляр типа + /// Type + /// Ctor args + /// Instance private object MakeInstance(Type type, object[] args) { ConstructorInfo constructor = null; @@ -331,10 +328,10 @@ namespace ZeroLevel.Patterns.DependencyInjection } } /// - /// Регистрация разрешения зависимости + /// Dependency resolution registration /// - /// Тип контракта - /// Метаданные разрешения + /// Contract + /// Dependency resolving metadata private void Register(Type contractType, ResolveTypeInfo resolveType) { try @@ -357,14 +354,12 @@ namespace ZeroLevel.Patterns.DependencyInjection if (resolveType.IsDefault && _resolvingMap[contractType].Any(it => it.IsDefault)) { - throw new Exception( - string.Format("Default resolve type already has been defined. Contract: {0}", contractType.FullName)); + throw new Exception($"Default resolve type already has been defined. Contract: {contractType.FullName}"); } if (_resolvingMap[contractType]. Any(it => it.ResolveKey.Equals(resolveType.ResolveKey, StringComparison.OrdinalIgnoreCase))) { - throw new Exception( - string.Format("Resolve type with the same name '{0}' already has been defined. Contract: {1}", resolveType.ResolveKey, contractType.FullName)); + throw new Exception($"Resolve type with the same name '{resolveType.ResolveKey}' already has been defined. Contract: { contractType.FullName}"); } } try @@ -590,10 +585,10 @@ namespace ZeroLevel.Patterns.DependencyInjection #region Register instance /// - /// Регистрация готового экземпляра (синглтон) + /// Register singletone /// - /// Тип контракта - /// Экземпляр + /// Contract + /// Instance public void Register(TContract implementation) { var resolveType = new ResolveTypeInfo @@ -961,8 +956,7 @@ namespace ZeroLevel.Patterns.DependencyInjection { var resolve = GetResolvedType(type, resolveName); if (null == resolve.Item1) - throw new KeyNotFoundException(string.Format("Can'r resolve type {0} on key '{1}'", - type.FullName, resolveName)); + throw new KeyNotFoundException($"Can'r resolve type {type.FullName} on key '{resolveName}'"); // Detect instance type try { @@ -974,9 +968,7 @@ namespace ZeroLevel.Patterns.DependencyInjection } catch (Exception ex) { - throw new Exception( - string.Format("Can't create instance for type {0} for resolved dependency {1} by key {2}", - type.FullName, type.FullName, resolveName), ex); + throw new Exception($"Can't create instance for type {type.FullName} for resolved dependency {type.FullName} by key {resolveName}", ex); } } #endregion @@ -1069,8 +1061,7 @@ namespace ZeroLevel.Patterns.DependencyInjection catch (Exception ex) { Log.SystemWarning( - string.Format("Не удалось создать экземпляр типа {0} для разрешения зависимости типа {1} по ключу {2}", - type.FullName, type.FullName, resolveName), ex); + $"Can't create type '{type.FullName}' instance for resolve dependency with contract type '{type.FullName}' and dependency name '{resolveName}'", ex); } result = null; return false; @@ -1079,7 +1070,7 @@ namespace ZeroLevel.Patterns.DependencyInjection #region Composition /// - /// Заполнение полей и свойств объекта отмеченных флагом автоподставновки значений из параметров контейнера + /// Filling in the fields and properties of an object with auto-set values flagged from the container parameters /// private void FillParametrizedFieldsAndProperties(object instance) { @@ -1165,7 +1156,10 @@ namespace ZeroLevel.Patterns.DependencyInjection Compose(instanse, recursive); return true; } - catch { } + catch (Exception ex) + { + Log.SystemError(ex, $"[Container] TryCompose error. Instance: '{instanse?.GetType()?.FullName ?? string.Empty}'. Recursive: {recursive}"); + } return false; } #endregion @@ -1184,7 +1178,10 @@ namespace ZeroLevel.Patterns.DependencyInjection { (item.SharedInstance as IDisposable)?.Dispose(); } - catch { } + catch (Exception ex) + { + Log.SystemError(ex, $"[Container] Singletone dispose error. Instance: '{item?.GetType()?.FullName ?? string.Empty}'"); + } if (item.GenericInstanceCachee != null) { foreach (var gitem in item.GenericInstanceCachee.Values) @@ -1193,12 +1190,19 @@ namespace ZeroLevel.Patterns.DependencyInjection { (gitem as IDisposable)?.Dispose(); } - catch { } + catch(Exception ex) + { + Log.SystemError(ex, $"[Container] Generic singletone dispose error. Instance: '{gitem?.GetType()?.FullName ?? string.Empty}'"); + } } } } } } + catch (Exception ex) + { + Log.SystemError(ex, $"[Container] Dispose error"); + } finally { _rwLock.ExitWriteLock(); diff --git a/ZeroLevel/Services/DependencyInjection/Contracts/ICompositionProvider.cs b/ZeroLevel/Services/DependencyInjection/Contracts/ICompositionProvider.cs index fcceadc..5c8f154 100644 --- a/ZeroLevel/Services/DependencyInjection/Contracts/ICompositionProvider.cs +++ b/ZeroLevel/Services/DependencyInjection/Contracts/ICompositionProvider.cs @@ -1,21 +1,21 @@ namespace ZeroLevel.Patterns.DependencyInjection { /// - /// Интерфейс с методами проведения композиций + /// Provides object composition /// public interface ICompositionProvider { #region Composition /// - /// Композиция, выполняет подстановку зарегистрированных контрактов в полях и свойствах объекта + /// Object compositions, insert contract implementation /// - /// Инстанс объекта + /// Object instance void Compose(object instanse, bool recursive = true); /// - /// Безопасная композиция, выполняет подстановку зарегистрированных контрактов в полях и свойствах объекта + /// Object compositions, insert contract implementation /// - /// Инстанс объекта - /// /// false - при сбое в попытке композиции объекта + /// Object instance + /// /// false if composition fault bool TryCompose(object instanse, bool recursive = true); #endregion } diff --git a/ZeroLevel/Services/DependencyInjection/Contracts/IContainerInstanceRegister.cs b/ZeroLevel/Services/DependencyInjection/Contracts/IContainerInstanceRegister.cs index 11214f9..e99397d 100644 --- a/ZeroLevel/Services/DependencyInjection/Contracts/IContainerInstanceRegister.cs +++ b/ZeroLevel/Services/DependencyInjection/Contracts/IContainerInstanceRegister.cs @@ -3,37 +3,37 @@ namespace ZeroLevel.Patterns.DependencyInjection { /// - /// Интерфейс с методами регистрации зависимостей с явным указанием экземпляров - /// (синглтон) + /// Methods for register contact implementations + /// (singletone) /// public interface IContainerInstanceRegister { #region Register instance /// - /// Регистрация готового экземпляра (синглтон) + /// Register instance for contract . (singletone) /// - /// Тип контракта - /// Экземпляр + /// Contract + /// Instance void Register(TContract implementation); /// - /// Регистрация готового экземпляра (синглтон) + /// Register instance for contract . (singletone) /// - /// Тип контракта - /// Экземпляр - /// Имя разрешения зависимости + /// Contract + /// Instance + /// Dependency name void Register(TContract implementation, string resolveName); /// - /// Регистрация готового экземпляра (синглтон) + /// Register instance for contract (singletone) /// - /// Тип контракта - /// Экземпляр + /// Contract + /// Instance void Register(Type contractType, object implementation); /// - /// Регистрация готового экземпляра (синглтон) + /// Register instance for contract (singletone) /// - /// Тип контракта - /// Имя разрешения зависимости - /// Экземпляр + /// Contract + /// Dependency name + /// Instance void Register(Type contractType, string resolveName, object implementation); #endregion } diff --git a/ZeroLevel/Services/DependencyInjection/Contracts/IContainerRegister.cs b/ZeroLevel/Services/DependencyInjection/Contracts/IContainerRegister.cs index 3fcee5f..75a00a8 100644 --- a/ZeroLevel/Services/DependencyInjection/Contracts/IContainerRegister.cs +++ b/ZeroLevel/Services/DependencyInjection/Contracts/IContainerRegister.cs @@ -3,293 +3,293 @@ namespace ZeroLevel.Patterns.DependencyInjection { /// - /// Интерфейс с методами регистрации зависимостей с указанием типов контракта и зависимости - /// (синглтоны и мультитоны) + /// Methods for register contact resolvings + /// (singletones and multitones) /// public interface IContainerRegister : IDisposable { #region Register /// - /// Регистрация разрешения зависимости + /// Dependency resolution registration /// - /// Тип контракта - /// Тип разрешения + /// Contract + /// Dependency resolution void Register(); /// - /// Регистрация разрешения зависимости + /// Dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости + /// Contract + /// Dependency resolution + /// Dependency name void Register(string resolveName); /// - /// Регистрация разрешения зависимости + /// Dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// true - для синглтонов + /// Contract + /// Dependency resolution + /// true - for singletone void Register(bool shared); /// - /// Регистрация разрешения зависимости + /// Dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// true - для синглтонов + /// Contract + /// Dependency resolution + /// Dependency name + /// true - for singletone void Register(string resolveName, bool shared); /// - /// Регистрация разрешения зависимости + /// Dependency resolution registration /// - /// Тип контракта - /// Тип разрешения + /// Contract + /// Dependency resolution void Register(Type contractType, Type implementationType); /// - /// Регистрация разрешения зависимости + /// Dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости + /// Contract + /// Dependency resolution + /// Dependency name void Register(Type contractType, Type implementationType, string resolveName); /// - /// Регистрация разрешения зависимости + /// Dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// true - для синглтонов + /// Contract + /// Dependency resolution + /// true - for singletone void Register(Type contractType, Type implementationType, bool shared); /// - /// Регистрация разрешения зависимости + /// Dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// true - для синглтонов + /// Contract + /// Dependency resolution + /// Dependency name + /// true - for singletone void Register(Type contractType, Type implementationType, string resolveName, bool shared); #endregion #region Register with parameters /// - /// Регистрация разрешения зависимости с указанием параметров конструктора + /// Dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Аргументы конструктора + /// Contract + /// Dependency resolution + /// Ctor args void ParameterizedRegister(object[] constructorParameters); /// - /// Регистрация разрешения зависимости с указанием параметров конструктора + /// Dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// Аргументы конструктора + /// Contract + /// Dependency resolution + /// Dependency name + /// Ctor args void ParameterizedRegister(string resolveName, object[] constructorParameters); /// - /// Регистрация разрешения зависимости с указанием параметров конструктора + /// Dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// true - для синглтонов - /// Аргументы конструктора + /// Contract + /// Dependency resolution + /// true - for singletone + /// Ctor args void ParameterizedRegister(bool shared, object[] constructorParameters); /// - /// Регистрация разрешения зависимости с указанием параметров конструктора + /// Dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// true - для синглтонов - /// Аргументы конструктора + /// Contract + /// Dependency resolution + /// Dependency name + /// true - for singletone + /// Ctor args void ParameterizedRegister(string resolveName, bool shared, object[] constructorParameters); /// - /// Регистрация разрешения зависимости с указанием параметров конструктора + /// Dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Аргументы конструктора + /// Contract + /// Dependency resolution + /// Ctor args void ParameterizedRegister(Type contractType, Type implementationType, object[] constructorParameters); /// - /// Регистрация разрешения зависимости с указанием параметров конструктора + /// Dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// Аргументы конструктора + /// Contract + /// Dependency resolution + /// Dependency name + /// Ctor args void ParameterizedRegister(Type contractType, Type implementationType, string resolveName, object[] constructorParameters); /// - /// Регистрация разрешения зависимости с указанием параметров конструктора + /// Dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// true - для синглтонов - /// Аргументы конструктора + /// Contract + /// Dependency resolution + /// true - for singletone + /// Ctor args void ParameterizedRegister(Type contractType, Type implementationType, bool shared, object[] constructorParameters); /// - /// Регистрация разрешения зависимости с указанием параметров конструктора + /// Dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// true - для синглтонов - /// Аргументы конструктора + /// Contract + /// Dependency resolution + /// Dependency name + /// true - for singletone + /// Ctor args void ParameterizedRegister(Type contractType, Type implementationType, string resolveName, bool shared, object[] constructorParameters); #endregion #region Safe register /// - /// Безопасная регистрация разрешения зависимости + /// Safe dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Error handler + /// true - registration successfully completed bool TryRegister(Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости + /// Safe dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Dependency name + /// Error handler + /// true - registration successfully completed bool TryRegister(string resolveName, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости + /// Safe dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// true - для синглтонов - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// true - for singletone + /// Error handler + /// true - registration successfully completed bool TryRegister(bool shared, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости + /// Safe dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// true - для синглтонов - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Dependency name + /// true - for singletone + /// Error handler + /// true - registration successfully completed bool TryRegister(string resolveName, bool shared, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости + /// Safe dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Error handler + /// true - registration successfully completed bool TryRegister(Type contractType, Type implementationType, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости + /// Safe dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Dependency name + /// Error handler + /// true - registration successfully completed bool TryRegister(Type contractType, Type implementationType, string resolveName, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости + /// Safe dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// true - для синглтонов - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// true - for singletone + /// Error handler + /// true - registration successfully completed bool TryRegister(Type contractType, Type implementationType, bool shared, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости + /// Safe dependency resolution registration /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// true - для синглтонов - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Dependency name + /// true - for singletone + /// Error handler + /// true - registration successfully completed bool TryRegister(Type contractType, Type implementationType, string resolveName, bool shared, Action fallback = null); #endregion #region Safe register with parameters /// - /// Безопасная регистрация разрешения зависимости с указанием параметров конструктора + /// Safe dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Аргументы конструктора - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Ctor args + /// Error handler + /// true - registration successfully completed bool TryParameterizedRegister(object[] constructorParameters, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости с указанием параметров конструктора + /// Safe dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// Аргументы конструктора - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Dependency name + /// Ctor args + /// Error handler + /// true - registration successfully completed bool TryParameterizedRegister(string resolveName, object[] constructorParameters, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости с указанием параметров конструктора + /// Safe dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// true - для синглтонов - /// Аргументы конструктора - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// true - for singletone + /// Ctor args + /// Error handler + /// true - registration successfully completed bool TryParameterizedRegister(bool shared, object[] constructorParameters, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости с указанием параметров конструктора + /// Safe dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// true - для синглтонов - /// Аргументы конструктора - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Dependency name + /// true - for singletone + /// Ctor args + /// Error handler + /// true - registration successfully completed bool TryParameterizedRegister(string resolveName, bool shared, object[] constructorParameters, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости с указанием параметров конструктора + /// Safe dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Аргументы конструктора - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Ctor args + /// Error handler + /// true - registration successfully completed bool TryParameterizedRegister(Type contractType, Type implementationType, object[] constructorParameters, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости с указанием параметров конструктора + /// Safe dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// Аргументы конструктора - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Dependency name + /// Ctor args + /// Error handler + /// true - registration successfully completed bool TryParameterizedRegister(Type contractType, Type implementationType, string resolveName, object[] constructorParameters, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости с указанием параметров конструктора + /// Safe dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// true - для синглтонов - /// Аргументы конструктора - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// true - for singletone + /// Ctor args + /// Error handler + /// true - registration successfully completed bool TryParameterizedRegister(Type contractType, Type implementationType, bool shared, object[] constructorParameters, Action fallback = null); /// - /// Безопасная регистрация разрешения зависимости с указанием параметров конструктора + /// Safe dependency resolution registration with constructor parameters /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// true - для синглтонов - /// Аргументы конструктора - /// Обработчик исключения - /// true - в случае успешной регистрации + /// Contract + /// Dependency resolution + /// Dependency name + /// true - for singletone + /// Ctor args + /// Error handler + /// true - registration successfully completed bool TryParameterizedRegister(Type contractType, Type implementationType, string resolveName, bool shared, object[] constructorParameters, Action fallback = null); #endregion } diff --git a/ZeroLevel/Services/DependencyInjection/Contracts/IParameterStorage.cs b/ZeroLevel/Services/DependencyInjection/Contracts/IParameterStorage.cs index c01be96..04d7006 100644 --- a/ZeroLevel/Services/DependencyInjection/Contracts/IParameterStorage.cs +++ b/ZeroLevel/Services/DependencyInjection/Contracts/IParameterStorage.cs @@ -3,69 +3,65 @@ namespace ZeroLevel.Patterns.DependencyInjection { /// - /// Интерфейс с методами для реализации хранения параметров - /// (хранилище ключ-значение, где в качестве ключа используется сущность типа string, а в качестве значения объект любого типа) + /// DI parameters stogare (string key and anytype value) /// public interface IParameterStorage { #region IEverythingStorage /// - /// Сохранение параметра + /// Save parameter /// - /// Тип параметра - /// Ключ - /// Значение параметра + /// Parameter type + /// Key + /// Parameter value void Save(string key, T value); /// - /// Сохранение или обновление параметра + /// Save or update parameter /// - /// Тип параметра - /// Ключ - /// Значение параметра + /// Parameter type + /// Key + /// Parameter value void SaveOrUpdate(string key, T value); /// - /// Безопасное сохранение параметра + /// Safe save parameter /// - /// Тип параметра - /// Ключ - /// Значение параметра - /// true - в случае успеха + /// Parameter type + /// Key + /// Parameter value bool TrySave(string key, T value); /// - /// Удаление параметра + /// Remove parameter by key /// - /// Тип параметра - /// Ключ + /// Parameter type + /// Key void Remove(string key); /// - /// Безопасное удаление параметра + /// Safe remove parameter by key /// - /// Тип параметра - /// Ключ - /// true - в случае успеха + /// Parameter type + /// Key bool TryRemove(string key); /// - /// Запрос сохраненного параметра + /// Get parameter value by key /// - /// Тип параметра - /// Ключ - /// Значение параметра + /// Parameter type + /// Key + /// Parameter value T Get(string key); T GetOrDefault(string key); T GetOrDefault(string key, T defaultValue); /// - /// Запрос сохраненного параметра + /// Get parameter value by key /// - /// Тип параметра - /// Ключ - /// Значение параметра + /// Parameter type + /// Key + /// Parameter value object Get(Type type, string key); /// - /// Проверка наличия параметра с указанным именем + /// Check for parameter existence by key /// - /// Тип параметра - /// Ключ - /// Указывает наличие параметра с заданным именем + /// Parameter type + /// Key bool Contains(string key); #endregion } diff --git a/ZeroLevel/Services/DependencyInjection/Contracts/IPoolContainer.cs b/ZeroLevel/Services/DependencyInjection/Contracts/IPoolContainer.cs deleted file mode 100644 index 4cbbe7f..0000000 --- a/ZeroLevel/Services/DependencyInjection/Contracts/IPoolContainer.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; - -namespace ZeroLevel.Patterns.DependencyInjection -{ - /// - /// Интерфейс с методами для реализации паттерна пул объектов в контейнере - /// - public interface IPoolContainer - { - #region Register poolable dependencies - /// - /// Регистрация пула - /// - /// Тип контракта - /// Начальное количество объектов в пуле - /// Максимальное количество объектов в пуле (при -1 пул не ограничен) - void RegisterPool(int initialCount, int capacity); - /// - /// Регистрация разрешения зависимости - /// - /// Тип контракта - /// Тип разрешения - void RegisterPoolable(); - /// - /// Регистрация разрешения зависимости - /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - void RegisterPoolable(string resolveName); - /// - /// Регистрация разрешения зависимости - /// - /// Тип контракта - /// Тип разрешения - void RegisterPoolable(Type contractType, Type implementationType); - /// - /// Регистрация разрешения зависимости - /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - void RegisterPoolable(Type contractType, Type implementationType, string resolveName); - /// - /// Регистрация разрешения зависимости - /// - /// Тип контракта - /// Экземпляр - void RegisterPoolable(TContract implementation); - /// - /// Регистрация разрешения зависимости - /// - /// Тип контракта - /// Экземпляр - void RegisterPoolable(Type contractType, object implementation); - #endregion - - #region Register poolable parametrizied dependencies - /// - /// Регистрация разрешения зависимости с указанием параметров конструктора - /// - /// Тип контракта - /// Тип разрешения - /// Аргументы конструктора - void RegisterPoolableParametrizied(object[] constructorParameters); - /// - /// Регистрация разрешения зависимости с указанием параметров конструктора - /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// Аргументы конструктора - void RegisterPoolableParametrizied(string resolveName, object[] constructorParameters); - /// - /// Регистрация разрешения зависимости с указанием параметров конструктора - /// - /// Тип контракта - /// Тип разрешения - /// Аргументы конструктора - void RegisterPoolableParametrizied(Type contractType, Type implementationType, object[] constructorParameters); - /// - /// Регистрация разрешения зависимости с указанием параметров конструктора - /// - /// Тип контракта - /// Тип разрешения - /// Имя разрешения зависимости - /// Аргументы конструктора - void RegisterPoolableParametrizied(Type contractType, Type implementationType, string resolveName, object[] constructorParameters); - #endregion - } -} diff --git a/ZeroLevel/Services/DependencyInjection/Contracts/IResolver.cs b/ZeroLevel/Services/DependencyInjection/Contracts/IResolver.cs index ce42421..a1c2808 100644 --- a/ZeroLevel/Services/DependencyInjection/Contracts/IResolver.cs +++ b/ZeroLevel/Services/DependencyInjection/Contracts/IResolver.cs @@ -3,107 +3,107 @@ namespace ZeroLevel.Patterns.DependencyInjection { /// - /// Интерфейс с методами разрешений зависимостей + /// Dependency resolver /// public interface IResolver { #region Activator /// - /// Создание экземпляра объекта указанного типа + /// Creating an instance of an object of the specified type /// - /// Тип объекта - /// Имя разрешения зависимости - /// Экземпляр объекта + /// Contract or instance type + /// Dependency name + /// Instance T CreateInstance(string resolveName = ""); /// - /// Создание экземпляра объекта указанного типа + /// Creating an instance of an object of the specified type /// - /// Тип объекта - /// Аргументы конструктора - /// Имя разрешения зависимости - /// Экземпляр объекта + /// Contract or instance type + /// Ctor agrs + /// Dependency name + /// Instance T CreateInstance(object[] args, string resolveName = ""); /// - /// Создание экземпляра объекта указанного типа + /// Creating an instance of an object of the specified type /// - /// Тип объекта - /// Имя разрешения зависимости - /// Экземпляр объекта + /// Contract or instance type + /// Dependency name + /// Instance object CreateInstance(Type type, string resolveName = ""); /// - /// Создание экземпляра объекта указанного типа + /// Creating an instance of an object of the specified type /// - /// Тип объекта - /// Аргументы конструктора - /// Имя разрешения зависимости - /// Экземпляр объекта + /// Contract or instance type + /// Ctor agrs + /// Dependency name + /// Instance object CreateInstance(Type type, object[] args, string resolveName = ""); #endregion #region Resolving /// - /// Разрешение зависимости + /// Dependency resolve /// - /// Тип контракта - /// Указание провести композицию при построении объектов - /// Инстанс + /// Contract + /// Compose the object when true + /// Instance T Resolve(bool compose = true); /// - /// Разрешение зависимости + /// Dependency resolve /// - /// Тип контракта - /// Имя разрешения зависимости - /// Указание провести композицию при построении объектов - /// Инстанс + /// Contract + /// Dependency name + /// Compose the object when true + /// Instance T Resolve(string resolveName, bool compose = true); /// - /// Разрешение зависимости + /// Dependency resolve /// - /// Тип контракта - /// Аргументы конструктора - /// Указание провести композицию при построении объектов - /// Инстанс + /// Contract + /// Ctor agrs + /// Compose the object when true + /// Instance T Resolve(object[] args, bool compose = true); /// - /// Разрешение зависимости + /// Dependency resolve /// - /// Тип контракта - /// Имя разрешения зависимости - /// Аргументы конструктора - /// Указание провести композицию при построении объектов - /// Инстанс + /// Contract + /// Dependency name + /// Ctor agrs + /// Compose the object when true + /// Instance T Resolve(string resolveName, object[] args, bool compose = true); /// - /// Разрешение зависимости + /// Dependency resolve /// - /// Тип контракта - /// Указание провести композицию при построении объектов - /// Инстанс + /// Contract + /// Compose the object when true + /// Instance object Resolve(Type type, bool compose = true); /// - /// Разрешение зависимости + /// Dependency resolve /// - /// Тип контракта - /// Имя разрешения зависимости - /// Указание провести композицию при построении объектов - /// Инстанс + /// Contract + /// Dependency name + /// Compose the object when true + /// Instance object Resolve(Type type, string resolveName, bool compose = true); /// - /// Разрешение зависимости + /// Dependency resolve /// - /// Тип контракта - /// Аргументы конструктора - /// Указание провести композицию при построении объектов - /// Инстанс + /// Contract + /// Ctor agrs + /// Compose the object when true + /// Instance object Resolve(Type type, object[] args, bool compose = true); /// - /// Разрешение зависимости + /// Dependency resolve /// - /// Тип контракта - /// Имя разрешения зависимости - /// Аргументы конструктора - /// Указание провести композицию при построении объектов - /// Инстанс + /// Contract + /// Dependency name + /// Ctor agrs + /// Compose the object when true + /// Instance object Resolve(Type type, string resolveName, object[] args, bool compose = true); #endregion diff --git a/ZeroLevel/Services/DependencyInjection/Internal/ConstructorMetadata.cs b/ZeroLevel/Services/DependencyInjection/Internal/ConstructorMetadata.cs index eaac6c6..e98a6dc 100644 --- a/ZeroLevel/Services/DependencyInjection/Internal/ConstructorMetadata.cs +++ b/ZeroLevel/Services/DependencyInjection/Internal/ConstructorMetadata.cs @@ -6,7 +6,7 @@ using System.Reflection; namespace ZeroLevel.Patterns.DependencyInjection { /// - /// Метаданные конструктора + /// Constructor metadata /// internal class ConstructorMetadata { @@ -26,16 +26,16 @@ namespace ZeroLevel.Patterns.DependencyInjection var resolveAttribute = p.GetCustomAttribute(); var kind = (parameterAttribute != null) ? ConstructorParameterKind.Parameter : - (resolveAttribute != null) ? ConstructorParameterKind.Resolve : ConstructorParameterKind.None; + (resolveAttribute != null) ? ConstructorParameterKind.Dependency : ConstructorParameterKind.None; return new ConstructorParameter { Type = p.ParameterType, ParameterKind = kind, ParameterResolveName = (kind == ConstructorParameterKind.Parameter) ? parameterAttribute?.Name ?? p.Name : - (kind == ConstructorParameterKind.Resolve) ? resolveAttribute?.ResolveName : null, + (kind == ConstructorParameterKind.Dependency) ? resolveAttribute?.ResolveName : null, ParameterResolveType = (kind == ConstructorParameterKind.Parameter) ? parameterAttribute?.Type ?? p.ParameterType : - (kind == ConstructorParameterKind.Resolve) ? resolveAttribute?.ContractType ?? p.ParameterType : null, + (kind == ConstructorParameterKind.Dependency) ? resolveAttribute?.ContractType ?? p.ParameterType : null, IsNullable = IsNullable(p.ParameterType) }; }).ToList(); @@ -48,11 +48,11 @@ namespace ZeroLevel.Patterns.DependencyInjection return false; // value-type } /// - /// Определение, подходит ли конструктор под указанные аргументы + /// Determining whether the constructor is suitable for the specified arguments /// - /// Аргументы - /// Подготовленные массив аргументов для вызова конструктора - /// true - если конструктор можно вызвать с переданными аргументами + /// Arguments + /// Prepared arguments for constructor call + /// true - if the constructor can be called with the arguments passed public bool IsMatch(object[] args, out object[] parameters) { parameters = null; @@ -67,7 +67,7 @@ namespace ZeroLevel.Patterns.DependencyInjection case ConstructorParameterKind.Parameter: parameters[i] = _parent.Get(Parameters[i].ParameterResolveType, Parameters[i].ParameterResolveName); break; - case ConstructorParameterKind.Resolve: + case ConstructorParameterKind.Dependency: parameters[i] = _parent.Resolve(Parameters[i].ParameterResolveType, Parameters[i].ParameterResolveName); break; default: diff --git a/ZeroLevel/Services/DependencyInjection/Internal/ConstructorParameter.cs b/ZeroLevel/Services/DependencyInjection/Internal/ConstructorParameter.cs index dad1334..e8955e4 100644 --- a/ZeroLevel/Services/DependencyInjection/Internal/ConstructorParameter.cs +++ b/ZeroLevel/Services/DependencyInjection/Internal/ConstructorParameter.cs @@ -3,47 +3,47 @@ namespace ZeroLevel.Patterns.DependencyInjection { /// - /// Тип аргумента конструктора в контексте иньекции зависимостей + /// Constructor argument type /// internal enum ConstructorParameterKind { /// - /// Аргумент задается из переданных значений + /// Constant /// None, /// - /// Аргумент задается из параметров контейнера + /// DI parameter /// Parameter, /// - /// Аргумент задается разрешением зависимости + /// Dependency /// - Resolve + Dependency } /// - /// Метаданные для описания аргумента конструктора + /// Constructor argument metadata /// internal sealed class ConstructorParameter { /// - /// Тип аргумента в рамках DI + /// Argument DI-type /// public ConstructorParameterKind ParameterKind; /// - /// Тип для определения аргумента через DI + /// Argument contract type /// public Type ParameterResolveType; /// - /// Имя для определения аргумента через DI + /// Dependency name /// public string ParameterResolveName; /// - /// Флаг определяющий допустимость записи null в качестве значения аргумента + /// Allow null /// public bool IsNullable; /// - /// Тип аргумента + /// Argument CLR type /// public Type Type; } diff --git a/ZeroLevel/Services/DependencyInjection/Internal/IPoolable.cs b/ZeroLevel/Services/DependencyInjection/Internal/IPoolable.cs deleted file mode 100644 index 9428cca..0000000 --- a/ZeroLevel/Services/DependencyInjection/Internal/IPoolable.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZeroLevel.Patterns.DependencyInjection -{ - public interface IPoolable - { - T Instance { get; } - void Cleanup(); - void Release(); - } -} diff --git a/ZeroLevel/Services/DependencyInjection/Internal/ResolveTypeInfo.cs b/ZeroLevel/Services/DependencyInjection/Internal/ResolveTypeInfo.cs index 0359813..c67a8b5 100644 --- a/ZeroLevel/Services/DependencyInjection/Internal/ResolveTypeInfo.cs +++ b/ZeroLevel/Services/DependencyInjection/Internal/ResolveTypeInfo.cs @@ -4,40 +4,40 @@ using System.Collections.Generic; namespace ZeroLevel.Patterns.DependencyInjection { /// - /// Метаданные разрешения зависимости + /// Dependency resolving metadata /// internal sealed class ResolveTypeInfo { /// - /// Разрешение зависимости по умолчанию + /// Default - without dependency name /// public bool IsDefault; /// - /// Создается только один экземпляр (в случае true) + /// Singletone when true /// public bool IsShared; /// - /// Тип инстанса (в том числе обобщенный) + /// Instance type (may be generic) /// public Type ImplementationType; /// - /// Ключ определения зависимости + /// Dependency resolving key /// public string ResolveKey; /// - /// Кэш экземпляра + /// Instance cache /// public object SharedInstance; /// - /// Кэш обобщенных типов + /// Generic types cahce /// public Dictionary GenericCachee; /// - /// Кэш обобщенных экземпляров + /// Generic instances cahce /// public Dictionary GenericInstanceCachee; /// - /// Параметры конструктора объекта + /// Constructor parameters /// public object[] ConstructorParameters; } diff --git a/ZeroLevel/Services/Drawing/TextPainter.cs b/ZeroLevel/Services/Drawing/TextPainter.cs index 2c26934..6e398bd 100644 --- a/ZeroLevel/Services/Drawing/TextPainter.cs +++ b/ZeroLevel/Services/Drawing/TextPainter.cs @@ -6,7 +6,7 @@ namespace ZeroLevel.Services.Drawing { public static class TextPainter { - #region Отрисовка текста вдоль линий + #region Drawing text along lines public static void DrawOnSegment(Graphics gr, Font font, PointF start_point, PointF end_point, diff --git a/ZeroLevel/Services/Extensions/ArrayExtensions.cs b/ZeroLevel/Services/Extensions/ArrayExtensions.cs index ae4c33b..097daf1 100644 --- a/ZeroLevel/Services/Extensions/ArrayExtensions.cs +++ b/ZeroLevel/Services/Extensions/ArrayExtensions.cs @@ -6,7 +6,7 @@ namespace ZeroLevel public static class ArrayExtensions { /// - /// Глубокое копирование массива + /// Deep copy array /// public static T[] DeepCopy(this T[] array) where T : ICloneable @@ -38,10 +38,8 @@ namespace ZeroLevel } } /// - /// Проверяет вхождение одного массива в другой + /// Checks whether one array is in another /// - /// Тиа элементов массивов - /// true - массив содержит указанный подмассив public static bool Contains(this T[] array, T[] candidate) { if (IsEmptyLocate(array, candidate)) diff --git a/ZeroLevel/Services/Extensions/CollectionComparsionExtensions.cs b/ZeroLevel/Services/Extensions/CollectionComparsionExtensions.cs index 7782f96..7957ff2 100644 --- a/ZeroLevel/Services/Extensions/CollectionComparsionExtensions.cs +++ b/ZeroLevel/Services/Extensions/CollectionComparsionExtensions.cs @@ -24,7 +24,7 @@ namespace ZeroLevel } /// - /// Проверяет на одинаковое содержание коллекции строк, в том числе по разному отсортированные + /// Checks for the same content of a collection of strings, including sorted in different ways /// public static bool StringEnumerableEquals(this IEnumerable A, IEnumerable B) { @@ -34,7 +34,7 @@ namespace ZeroLevel } /// - /// Проверяет на одинаковое содержание коллекций, в том числе по разному отсортированных + /// Checks for the same content of collections, including sorted in different ways /// public static bool NoOrderingEquals(this IEnumerable A, IEnumerable B) { @@ -51,7 +51,7 @@ namespace ZeroLevel } /// - /// Проверяет на одинаковое содержание коллекций + /// Checks for the same content collections /// public static bool OrderingEquals(this IEnumerable A, IEnumerable B) { @@ -85,7 +85,7 @@ namespace ZeroLevel return true; } /// - /// Расчет хеша для коллекции + /// Calculate hash for collection /// public static int GetEnumHashCode(this IEnumerable A) { diff --git a/ZeroLevel/Services/Extensions/DateTimeExtensions.cs b/ZeroLevel/Services/Extensions/DateTimeExtensions.cs index b677b09..40299e6 100644 --- a/ZeroLevel/Services/Extensions/DateTimeExtensions.cs +++ b/ZeroLevel/Services/Extensions/DateTimeExtensions.cs @@ -5,10 +5,8 @@ namespace ZeroLevel public static class DateTimeExtensions { /// - /// Огругляет дату до указанного масштаба - /// - /// Необходимость: округление дат при сохранении в модель, которая будет использоваться для SqlServer, - /// т.к. sqlserver не может точность - Datetime values are rounded to increments of .000, .003, or .007 seconds + /// Rounds the date to the specified scale. + /// Example: sqlserver - Datetime values are rounded to increments of .000, .003, or .007 seconds /// public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan) { diff --git a/ZeroLevel/Services/Extensions/FPCommon.cs b/ZeroLevel/Services/Extensions/FPCommon.cs index 076a7f0..8ee5502 100644 --- a/ZeroLevel/Services/Extensions/FPCommon.cs +++ b/ZeroLevel/Services/Extensions/FPCommon.cs @@ -4,7 +4,7 @@ using System.Runtime.Serialization; namespace ZeroLevel.Services.Extensions { /// - /// Обобщенные возможности из ФП + /// FP /// public static class FPCommon { diff --git a/ZeroLevel/Services/Extensions/Monades.cs b/ZeroLevel/Services/Extensions/Monades.cs index 1206e12..3392056 100644 --- a/ZeroLevel/Services/Extensions/Monades.cs +++ b/ZeroLevel/Services/Extensions/Monades.cs @@ -2,9 +2,6 @@ namespace ZeroLevel { - /// - /// Сборник монад - /// public static class Monades { #region With diff --git a/ZeroLevel/Services/FileSystem/FSUtils.cs b/ZeroLevel/Services/FileSystem/FSUtils.cs index 280e8ce..c9aadcf 100644 --- a/ZeroLevel/Services/FileSystem/FSUtils.cs +++ b/ZeroLevel/Services/FileSystem/FSUtils.cs @@ -42,12 +42,12 @@ namespace ZeroLevel.Services.FileSystem } /// - /// Задает права доступа к каталогу для учетной записи + /// Sets the directory permissions for the account /// - /// Путь к каталогу - /// Аккаунт - /// Права доступа - /// Тип доступа + /// Directory path + /// Account + /// Access rights + /// Access type public static void SetupFolderPermission(string folderPath, string account, FileSystemRights right, AccessControlType controlType) { @@ -63,7 +63,7 @@ namespace ZeroLevel.Services.FileSystem private static string _invalid_path_characters = new string(Path.GetInvalidPathChars()); private static string _invalid_filename_characters = new string(Path.GetInvalidFileNameChars()); /// - /// Удаляет из переданного пути недопустимые символы + /// Removes invalid characters from the passed path /// public static string PathCorrection(string path) { @@ -82,7 +82,7 @@ namespace ZeroLevel.Services.FileSystem return new string(result, 0, index); } /// - /// Удаляет из переданного имени файла недопустимые символы + /// Removes invalid characters from the passed file name /// /// /// @@ -105,7 +105,7 @@ namespace ZeroLevel.Services.FileSystem #endregion /// - /// Выполняет проверку на доступность файла для обработки + /// Performs a file accessibility check for processing /// public static bool IsFileLocked(FileInfo file) { diff --git a/ZeroLevel/Services/FileSystem/FileArchive.cs b/ZeroLevel/Services/FileSystem/FileArchive.cs index a316588..e627dcc 100644 --- a/ZeroLevel/Services/FileSystem/FileArchive.cs +++ b/ZeroLevel/Services/FileSystem/FileArchive.cs @@ -227,20 +227,20 @@ namespace ZeroLevel.Services.FileSystem } while (_disposed == false); } /// - /// Сохранение текста в архив + /// Save text to archive /// - /// Текст - /// Имя файла в архиве (по умолчанию HH_mm_ss_fff_counter.{ext}) + /// Text + /// Archive file name (HH_mm_ss_fff_counter.{ext} by default) /// public void StoreText(string text, string subfolder_name = null, string file_name = null) { Apply(new StoreText(text, CreateArchiveFilePath(subfolder_name, file_name))); } /// - /// Сохранение указанного файла в архив + /// Saving the specified file to the archive /// - /// Путь к файлу - /// Имя файла в архиве (по умолчанию оригинальное имя файла) + /// File path + /// Archive file name (original file name by default) /// public void Store(string file_path, string subfolder_name = null, string file_name = null) { @@ -259,20 +259,20 @@ namespace ZeroLevel.Services.FileSystem } } /// - /// Сохранение данных из потока в архив + /// Saving data from stream to archive /// - /// Поток с данными для чтения - /// Имя файла в архиве (по умолчанию HH_mm_ss_fff_counter.{ext}) + /// Data stream for reading + /// Archive file name (HH_mm_ss_fff_counter.{ext} by default) /// public void Store(Stream stream, string subfolder_name = null, string file_name = null) { Apply(new StoreStream(stream, CreateArchiveFilePath(subfolder_name, file_name))); } /// - /// Сохранение данных в бинарном виде в архив + /// Saving data in binary form in the archive /// - /// Данные - /// Имя файла в архиве (по умолчанию HH_mm_ss_fff_counter.{ext}) + /// Data + /// Archive file name (HH_mm_ss_fff_counter.{ext} by default) /// public void StoreData(byte[] data, string subfolder_name = null, string file_name = null) { @@ -333,8 +333,7 @@ namespace ZeroLevel.Services.FileSystem if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); - FSUtils.SetupFolderPermission(path, - string.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName), + FSUtils.SetupFolderPermission(path,$"{Environment.UserDomainName}\\{Environment.UserName}", FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify, AccessControlType.Allow); } @@ -398,31 +397,31 @@ namespace ZeroLevel.Services.FileSystem } } /// - /// Сохранение текста в архив + /// Save text to archive /// - /// Текст - /// Имя файла в архиве (по умолчанию HH_mm_ss_fff_counter.{ext}) + /// Text + /// Archive file name (HH_mm_ss_fff_counter.{ext} by default) /// public void StoreText(string text, string name = null) { Apply(new StoreText(text, CreateArchiveFilePath(name))); } /// - /// Сохранение указанного файла в архив + /// Saving the specified file to the archive /// - /// Путь к файлу - /// Имя файла в архиве (по умолчанию оригинальное имя файла) + /// File path + /// Archive file name (original file name by default) /// public void Store(string file_path, string name = null) { Apply(new StoreFile(file_path, CreateArchiveFilePath(name))); } /// - /// охранение указанного файла в архив, синхронно + /// Sync saving the specified file to the archive /// - /// - /// - /// + /// File path + /// Archive file name (original file name by default) + /// public void Store(string file_path, bool immediate, string name = null) { if (immediate) @@ -435,10 +434,10 @@ namespace ZeroLevel.Services.FileSystem } } /// - /// Сохранение данных из потока в архив + /// Saving data from stream to archive /// - /// Поток с данными для чтения - /// Имя файла в архиве (по умолчанию HH_mm_ss_fff_counter.{ext}) + /// Data stream for reading + /// Archive file name (HH_mm_ss_fff_counter.{ext} by default) /// public void Store(Stream stream, string name = null) { @@ -447,8 +446,8 @@ namespace ZeroLevel.Services.FileSystem /// /// Сохранение данных в бинарном виде в архив /// - /// Данные - /// Имя файла в архиве (по умолчанию HH_mm_ss_fff_counter.{ext}) + /// Data + /// Archive file name (HH_mm_ss_fff_counter.{ext} by default) /// public void StoreData(byte[] data, string name = null) { @@ -475,7 +474,7 @@ namespace ZeroLevel.Services.FileSystem { Directory.CreateDirectory(path); FSUtils.SetupFolderPermission(path, - string.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName), + $"{Environment.UserDomainName}\\{Environment.UserName}", FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify, AccessControlType.Allow); } diff --git a/ZeroLevel/Services/FileSystem/PeriodicFileSystemWatcher.cs b/ZeroLevel/Services/FileSystem/PeriodicFileSystemWatcher.cs index 2ec9689..905c574 100644 --- a/ZeroLevel/Services/FileSystem/PeriodicFileSystemWatcher.cs +++ b/ZeroLevel/Services/FileSystem/PeriodicFileSystemWatcher.cs @@ -72,7 +72,7 @@ namespace ZeroLevel.Services.FileSystem } catch (Exception ex) { - Log.SystemError(ex, "Сбой при попытке перемещения файла '{0}' во временный каталог '{1}'", file, _temporaryFolder); + Log.SystemError(ex, $"[PeriodicFileSystemWatcher] Failed to attempt to move file '{file}' to temporary directory '{_temporaryFolder}'"); continue; } Log.Debug($"[PeriodicFileSystemWatcher] Handle file {file}"); @@ -87,12 +87,12 @@ namespace ZeroLevel.Services.FileSystem } catch (Exception ex) { - Log.SystemError(ex, "Сбой при обработке входного каталога '{0}'", _sourceFolder); + Log.SystemError(ex, $"[PeriodicFileSystemWatcher] Failed to process input directory '{_sourceFolder}'"); } } /// - /// Перемещение файла во временный каталог + /// Moving a file to a temporary directory /// public string MoveToTemporary(string from) { @@ -110,8 +110,7 @@ namespace ZeroLevel.Services.FileSystem return tempFile; } /// - /// Разрешение коллизий в именах файлов во временном каталоге - /// (требуется если в источнике могут появляться файлы в разное время с одинаковыми именами) + /// Resolving collisions in filenames in the temporary directory /// private static string TrySolveCollision(string file) { @@ -141,7 +140,7 @@ namespace ZeroLevel.Services.FileSystem throw new ArgumentException("folder"); } /// - /// Получение списка файлов из входного каталога + /// Getting a list of files from the input directory /// public string[] GetFilesFromSource() { @@ -150,7 +149,7 @@ namespace ZeroLevel.Services.FileSystem return files; } /// - /// Сравнение названий файлов + /// File Name Comparison /// private static int FileNameSortCompare(string x, string y) { diff --git a/ZeroLevel/Services/Impersonation/IImpersonationExecutor.cs b/ZeroLevel/Services/Impersonation/IImpersonationExecutor.cs index ebf172e..8622116 100644 --- a/ZeroLevel/Services/Impersonation/IImpersonationExecutor.cs +++ b/ZeroLevel/Services/Impersonation/IImpersonationExecutor.cs @@ -3,7 +3,7 @@ namespace ZeroLevel.Services.Impersonation { /// - /// Интерфейс для классов исполняющих произвольный код от прав пользователя или процесса + /// Interface for classes executing code from user or process rights /// public interface IImpersonationExecutor { diff --git a/ZeroLevel/Services/Impersonation/Impersonation.cs b/ZeroLevel/Services/Impersonation/Impersonation.cs index dd369e6..d5e04ab 100644 --- a/ZeroLevel/Services/Impersonation/Impersonation.cs +++ b/ZeroLevel/Services/Impersonation/Impersonation.cs @@ -7,7 +7,7 @@ using System.Security.Principal; namespace ZeroLevel.Services.Impersonation { /// - /// Класс реализует перевод исполнения программы на права указанного пользователя + /// The class implements the translation of the program execution to the rights of the specified user. /// [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)] [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] @@ -17,20 +17,20 @@ namespace ZeroLevel.Services.Impersonation #region Private methods /// - /// Назначение текущему процессу прав от указанного процесса, путем копирования его токена + /// Assigning rights to the current process from the specified process, by copying its token /// - /// Указатель на процесс + /// Process pointer private void ImpersonateByProcess(IntPtr hProcess) { MySafeTokenHandle token; if (!ImpersonationNativeMethods.OpenProcessToken(hProcess, ImpersonationNativeMethods.TokenDesiredAccess.TOKEN_DUPLICATE, out token)) - throw new ApplicationException("Не удалось получить токен процесса. Win32 код ошибки: " + Marshal.GetLastWin32Error()); + throw new ApplicationException("Failed to get the process token. Win32 error code: " + Marshal.GetLastWin32Error()); ImpersonateToken(token); } /// - /// Метод назначает текущему процессу дубликат переданного токена + /// The method assigns a duplicate token to the current process. /// - /// Токен + /// Token private void ImpersonateToken(MySafeTokenHandle token) { MySafeTokenHandle tokenDuplicate; @@ -50,19 +50,19 @@ namespace ZeroLevel.Services.Impersonation } } else - throw new Exception("Не удалось создать дубликат указанного токена. Win32 код ошибки: " + Marshal.GetLastWin32Error()); + throw new Exception("Failed to create a duplicate of the specified token. Win32 error code: " + Marshal.GetLastWin32Error()); } } #endregion #region Public methods /// - /// Вход от имени указанного пользователя + /// Login as a specified user /// - /// Имя пользователя - /// Домен - /// Пароль - /// false - если не удалось выполнить вход по указанным данным + /// User name + /// User domain + /// User password + /// false - if failed to log in with the specified data public void ImpersonateByUser(String userName, String domain, String password) { MySafeTokenHandle token; @@ -111,9 +111,9 @@ namespace ZeroLevel.Services.Impersonation } } /// - /// Копирование прав указанного процесса + /// Copying the rights of the specified process /// - /// Идентификатор процесса + /// Process id public void ImpersonateByProcess(int ProcessID) { Process[] myProcesses = Process.GetProcesses(); @@ -129,7 +129,7 @@ namespace ZeroLevel.Services.Impersonation #endregion /// - /// При освобождении рессурсов вернем предыдущего пользователя + /// When releasing resources, we will return the previous user right /// public void Dispose() { diff --git a/ZeroLevel/Services/Impersonation/ImpersonationNativeMethods.cs b/ZeroLevel/Services/Impersonation/ImpersonationNativeMethods.cs index 8add77b..7272d56 100644 --- a/ZeroLevel/Services/Impersonation/ImpersonationNativeMethods.cs +++ b/ZeroLevel/Services/Impersonation/ImpersonationNativeMethods.cs @@ -10,7 +10,7 @@ namespace ZeroLevel.Services.Impersonation { #region P/Invoke enums /// - /// Провайдер авторизации + /// Authorization provider /// public enum LogonProvider : int { @@ -23,7 +23,7 @@ namespace ZeroLevel.Services.Impersonation LOGON32_PROVIDER_DEFAULT = 0, } /// - /// Способ авторизации + /// Authorization method /// public enum LogonType : int { @@ -74,7 +74,7 @@ namespace ZeroLevel.Services.Impersonation LOGON32_LOGON_NEW_CREDENTIALS = 9, } /// - /// Желаемый уровень доступа к токену + /// Desired access level to token /// public struct TokenDesiredAccess { @@ -82,7 +82,7 @@ namespace ZeroLevel.Services.Impersonation public static uint STANDARD_RIGHTS_READ = 0x00020000; public static uint TOKEN_ASSIGN_PRIMARY = 0x0001; /// - /// Позволяет создать копию + /// Allows to create a copy /// public static uint TOKEN_DUPLICATE = 0x0002; public static uint TOKEN_IMPERSONATE = 0x0004; @@ -99,7 +99,7 @@ namespace ZeroLevel.Services.Impersonation TOKEN_ADJUST_SESSIONID); } /// - /// Тип безопасности применяется при операции дублирования токена(в текущей задаче) + /// The security type is used during the token duplication operation (in the current task) /// public enum SecurityImpersonationLevel : int { @@ -132,14 +132,14 @@ namespace ZeroLevel.Services.Impersonation #region P/Invoke /// - /// Авторизация от имени указанного пользователя + /// Authorization on behalf of the specified user /// - /// Имя пользователя - /// Домен в котором зарегистрирован пользователь - /// Пароль - /// Тип авторизации - /// Провайдер (всегда 0) - /// Токен - результат входа + /// Username + /// Domain + /// Password + /// Authorization Type + /// Provider (always 0) + /// Token - login result /// [DllImport("advapi32.dll")] internal static extern int LogonUserA(String lpszUserName, @@ -149,9 +149,9 @@ namespace ZeroLevel.Services.Impersonation int dwLogonProvider, out MySafeTokenHandle phToken); /// - /// Создание дубликата токена + /// Creating a duplicate token /// - /// Исходный токен + /// Original token /// /// /// @@ -164,11 +164,11 @@ namespace ZeroLevel.Services.Impersonation [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal static extern bool CloseHandle(IntPtr handle); /// - /// Попытка получения токена работающего процесса + /// Attempt to get a token running process /// - /// Указатель на процесс + /// Process pointer /// - /// Токен - результат + /// Token - result /// [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] diff --git a/ZeroLevel/Services/Impersonation/MySafeTokenHandle.cs b/ZeroLevel/Services/Impersonation/MySafeTokenHandle.cs index 01ec1da..ec56d63 100644 --- a/ZeroLevel/Services/Impersonation/MySafeTokenHandle.cs +++ b/ZeroLevel/Services/Impersonation/MySafeTokenHandle.cs @@ -5,7 +5,7 @@ using System.Security.Permissions; namespace ZeroLevel.Services.Impersonation { /// - /// Реализация безопасного указателя + /// Implementing a safe pointer /// [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] diff --git a/ZeroLevel/Services/Impersonation/ProcessImpersonationExecutor.cs b/ZeroLevel/Services/Impersonation/ProcessImpersonationExecutor.cs index 30f5747..21899e6 100644 --- a/ZeroLevel/Services/Impersonation/ProcessImpersonationExecutor.cs +++ b/ZeroLevel/Services/Impersonation/ProcessImpersonationExecutor.cs @@ -3,7 +3,7 @@ namespace ZeroLevel.Services.Impersonation { /// - /// Реализует исполнение произвольного кода от прав указанного процесса + /// Implements the execution of an code from the rights of the specified process /// public class ProcessImpersonationExecutor : IImpersonationExecutor @@ -21,11 +21,8 @@ namespace ZeroLevel.Services.Impersonation _pid = pid; } /// - /// Исполнение кода + /// Code execution /// - /// Тип передаваемого аргумента - /// Делегат - /// Аргумент public void ExecuteCode(Action action, T arg) { using (Impersonation imp = new Impersonation()) @@ -40,16 +37,14 @@ namespace ZeroLevel.Services.Impersonation } else { - throw new Exception("Нет данных для идентификации процесса. Для копирования прав процесса требуется указать его имя или идентификатор."); + throw new Exception("No data to identify the process. To copy the rights of a process, you must specify its name or identifier"); } action(arg); } } /// - /// Исполнение кода + /// Code execution /// - /// Тип передаваемого аргумента - /// Делегат public void ExecuteCode(Action action) { using (Impersonation imp = new Impersonation()) @@ -64,7 +59,7 @@ namespace ZeroLevel.Services.Impersonation } else { - throw new Exception("Нет данных для идентификации процесса. Для копирования прав процесса требуется указать его имя или идентификатор."); + throw new Exception("No data to identify the process. To copy the rights of a process, you must specify its name or identifier"); } action(); } diff --git a/ZeroLevel/Services/Impersonation/UserImpersonationExecutor.cs b/ZeroLevel/Services/Impersonation/UserImpersonationExecutor.cs index be89384..ba92b8e 100644 --- a/ZeroLevel/Services/Impersonation/UserImpersonationExecutor.cs +++ b/ZeroLevel/Services/Impersonation/UserImpersonationExecutor.cs @@ -3,7 +3,7 @@ namespace ZeroLevel.Services.Impersonation { /// - /// Класс исполняющий произвольный код с правами указанного пользователя + /// Class executing code with the rights of the specified user /// public class UserImpersonationExecutor : IImpersonationExecutor @@ -22,11 +22,8 @@ namespace ZeroLevel.Services.Impersonation } /// - /// Исполнение кода + /// Code execution /// - /// Тип передаваемого аргумента - /// Делегат - /// Аргумент public void ExecuteCode(Action action, T arg) { using (Impersonation imp = new Impersonation()) @@ -36,10 +33,8 @@ namespace ZeroLevel.Services.Impersonation } } /// - /// Исполнение кода + /// Code execution /// - /// Тип передаваемого аргумента - /// Делегат public void ExecuteCode(Action action) { using (Impersonation imp = new Impersonation()) diff --git a/ZeroLevel/Services/Invokation/InvokeWrapper.cs b/ZeroLevel/Services/Invokation/InvokeWrapper.cs index d6a7ea1..3895faf 100644 --- a/ZeroLevel/Services/Invokation/InvokeWrapper.cs +++ b/ZeroLevel/Services/Invokation/InvokeWrapper.cs @@ -8,31 +8,31 @@ using System.Text; namespace ZeroLevel.Services.Invokation { /// - /// Обертка для вызова методов + /// Method call wrapper /// public class InvokeWrapper : IInvokeWrapper { /// - /// Кэш делегатов + /// Cahce /// protected readonly Dictionary _invokeCachee = new Dictionary(); #region Static helpers /// - /// Создает скомпилированное выражение для быстрого вызова метода, возвращает идентификатор выражения и делегат для вызова + /// Creates a compiled expression for a quick method call, returns the identifier of the expression and a delegate for the call. /// - /// Оборачиваемый метод - /// Кортеж с идентификатором выражения и делегатом + /// Wrapped method + /// Expression ID and Delegate Tuple protected static Tuple CreateCompiledExpression(MethodInfo method) { - var targetArg = Expression.Parameter(typeof(object)); // Цель на которой происходит вызов - var argsArg = Expression.Parameter(typeof(object[])); // Аргументы метода + var targetArg = Expression.Parameter(typeof(object)); + var argsArg = Expression.Parameter(typeof(object[])); var parameters = method.GetParameters(); Expression body = Expression.Call( method.IsStatic ? null - : Expression.Convert(targetArg, method.DeclaringType), // тип в котором объявлен метод + : Expression.Convert(targetArg, method.DeclaringType), // the type in which the method is declared method, parameters.Select((p, i) => Expression.Convert(Expression.ArrayIndex(argsArg, Expression.Constant(i)), p.ParameterType))); @@ -46,10 +46,10 @@ namespace ZeroLevel.Services.Invokation } /// - /// Оборачивает вызов делегата + /// Wraps Delegate Call /// - /// Оборачиваемый делегат - /// Кортеж с идентификатором выражения и делегатом + /// Wrapped delegate + /// Expression ID and Delegate Tuple protected static Tuple CreateCompiledExpression(Delegate handler) { return CreateCompiledExpression(handler.GetMethodInfo()); @@ -60,10 +60,10 @@ namespace ZeroLevel.Services.Invokation #region Helpers /// - /// Идентификатр однозначно определяющий метод на уровне типа (но не на глобальном уровне) + /// ID uniquely identifying method at the type level (but not at the global level) /// - /// Имя метода - /// Типы аргументов метода + /// Method name + /// Method Argument Types /// internal static string CreateMethodIdentity(string name, params Type[] argsTypes) { @@ -190,10 +190,10 @@ namespace ZeroLevel.Services.Invokation #region Configure by MethodInfo /// - /// Вносит в кэш вызов указанного метода + /// Cache the specified method /// - /// Метод - /// Идентификатор для вызова + /// Method + /// Call ID public string Configure(MethodInfo method) { var invoke = CreateCompiledExpression(method); @@ -202,10 +202,10 @@ namespace ZeroLevel.Services.Invokation } /// - /// Вносит в кэш вызов указанного делегата + /// Cache the specified delegate /// - /// Делегат - /// Идентификатор вызова + /// Delegate + /// Call ID public string Configure(Delegate handler) { var invoke = CreateCompiledExpression(handler); @@ -230,7 +230,7 @@ namespace ZeroLevel.Services.Invokation #region Configuration /// - /// Наполнение кэша из списка методов с идентификаторами + /// Filling the cache from the list of methods with identifiers /// protected void Configure(IEnumerable> list) { @@ -241,7 +241,7 @@ namespace ZeroLevel.Services.Invokation } /// - /// Добавление вызова в кэш + /// Adding a call to the cache /// protected void Configure(Tuple invoke) { @@ -253,11 +253,11 @@ namespace ZeroLevel.Services.Invokation #region Invoking /// - /// Вызов статического метода по идентификатору, в случае отсутствия метода в кеше будет брошено исключение KeyNotFoundException + /// Calling a static method by identifier, if there is no method in the cache, a KeyNotFoundException exception will be thrown /// - /// Идентификатор метода - /// Аргументы метода - /// Результат выполнения + /// Call ID + /// Method Arguments + /// Execution result public object InvokeStatic(string identity, object[] args) { if (_invokeCachee.ContainsKey(identity)) @@ -269,12 +269,12 @@ namespace ZeroLevel.Services.Invokation } /// - /// Вызов метода по идентификатору, в случае отсутствия метода в кеше будет брошено исключение KeyNotFoundException + /// Calling a method by identifier; if there is no method in the cache, KeyNotFoundException will be thrown. /// - /// Инстанс на котором вызывается метод - /// Идентификатор метода - /// Аргументы метода - /// Результат выполнения + /// The instance on which the method is called + /// Call ID + /// Method Arguments + /// Execution result public object Invoke(object target, string identity, object[] args) { if (_invokeCachee.ContainsKey(identity)) @@ -282,7 +282,7 @@ namespace ZeroLevel.Services.Invokation return _invokeCachee[identity](target, args); } - throw new KeyNotFoundException(String.Format("Not found method with identity '{0}'", identity)); + throw new KeyNotFoundException($"Not found method with identity '{identity}'"); } public object Invoke(object target, string identity) @@ -292,15 +292,15 @@ namespace ZeroLevel.Services.Invokation return _invokeCachee[identity](target, null); } - throw new KeyNotFoundException(String.Format("Not found method with identity '{0}'", identity)); + throw new KeyNotFoundException($"Not found method with identity '{identity}'"); } /// - /// Выполнение статического закэшированного метода + /// Execution of a static cached method /// - /// Имя метода - /// Аргументы метода - /// /// Результат выполнения + /// Method name + /// Method Arguments + /// /// Execution result public object Invoke(string methodName, object[] args) { return InvokeStatic(CreateMethodIdentity(methodName, args.Select(a => a.GetType()).ToArray()), args); @@ -311,21 +311,21 @@ namespace ZeroLevel.Services.Invokation #region Helpers /// - /// Запрос идентификатора для метода + /// Request call id for method /// - /// Имя метода - /// Список типов аргументов метода - /// Идентификатор + /// Method name + /// Method argument type list + /// Call ID public string GetInvokerIdentity(string methodName, params Type[] argsTypes) { return CreateMethodIdentity(methodName, argsTypes); } /// - /// Запрос делегата оборачивающего метод + /// Request for delegate to wrap method /// - /// Идентификатор метода - /// Делегат + /// Call ID + /// Delegate public Invoker GetInvoker(string identity) { if (_invokeCachee.ContainsKey(identity)) @@ -337,11 +337,11 @@ namespace ZeroLevel.Services.Invokation } /// - /// Запрос делегата оборачивающего метод + /// Request for delegate to wrap method /// - /// Имя метода - /// Список типов аргументов метода - /// Делегат + /// Method name + /// Method argument type list + /// Delegate public Invoker GetInvoker(string methodName, params Type[] argsTypes) { return GetInvoker(CreateMethodIdentity(methodName, argsTypes)); diff --git a/ZeroLevel/Services/Invokation/Invoker.cs b/ZeroLevel/Services/Invokation/Invoker.cs index 03df5a7..a8a7820 100644 --- a/ZeroLevel/Services/Invokation/Invoker.cs +++ b/ZeroLevel/Services/Invokation/Invoker.cs @@ -1,10 +1,10 @@ namespace ZeroLevel.Services.Invokation { /// - /// Делегат описывающий вызов метода + /// Delegate describing the method call /// - /// Цель на которой вызывается метод - /// Аргументы метода - /// Результат + /// The target on which the method is called + /// Method Arguments + /// Result public delegate object Invoker(object target, params object[] args); } diff --git a/ZeroLevel/Services/Logging/ILog.cs b/ZeroLevel/Services/Logging/ILog.cs index da2791e..2a94025 100644 --- a/ZeroLevel/Services/Logging/ILog.cs +++ b/ZeroLevel/Services/Logging/ILog.cs @@ -5,39 +5,39 @@ namespace ZeroLevel.Services.Logging public interface ILog { /// - /// Вывод сообщения как есть, без добавления уровня логирования и даты + /// Message output as is, without adding a logging level and date /// void Raw(string line, params object[] args); /// - /// Сообщение + /// Message /// void Info(string line, params object[] args); /// - /// Предупреждение + /// Warning /// void Warning(string line, params object[] args); /// - /// Ошибка + /// Error /// void Error(string line, params object[] args); /// - /// Ошибка + /// Error /// void Error(Exception ex, string line, params object[] args); /// - /// Фатальный сбой + /// Fatal crash /// void Fatal(string line, params object[] args); /// - /// Фатальный сбой + /// Fatal crash /// void Fatal(Exception ex, string line, params object[] args); /// - /// Отладочная информация + /// Debug info /// void Debug(string line, params object[] args); /// - /// Низкоуровневая отладочная информация + /// Low Level Debug info /// void Verbose(string line, params object[] args); } diff --git a/ZeroLevel/Services/Logging/ILogMessageBuffer.cs b/ZeroLevel/Services/Logging/ILogMessageBuffer.cs index 5eed7c3..2239461 100644 --- a/ZeroLevel/Services/Logging/ILogMessageBuffer.cs +++ b/ZeroLevel/Services/Logging/ILogMessageBuffer.cs @@ -3,22 +3,19 @@ namespace ZeroLevel.Services.Logging { /// - /// Очередь сообщений для вывода в лог + /// Message queue for logging /// internal interface ILogMessageBuffer : IDisposable { /// - /// Количество сообщений в очереди + /// Number of messages in the queue /// long Count { get; } /// - /// Запись сообщения в очередь + /// Write message to the queue /// void Push(LogLevel level, string message); - /// - /// Запрос сообщения из очереди для вывода в лог, подразумевается блокирующая работа метода, - /// пока очередь пустая, метод ожидает появления сообщения не возвращая результат. - /// + Tuple Take(); } } diff --git a/ZeroLevel/Services/Logging/Implementation/EncryptedFileLog.cs b/ZeroLevel/Services/Logging/Implementation/EncryptedFileLog.cs index fcba1dd..8d21269 100644 --- a/ZeroLevel/Services/Logging/Implementation/EncryptedFileLog.cs +++ b/ZeroLevel/Services/Logging/Implementation/EncryptedFileLog.cs @@ -50,15 +50,15 @@ namespace ZeroLevel.Services.Logging.Implementation private readonly EncryptedFileLogOptions _options; private int _todayCountLogFiles = 0; /// - /// Текущий лог-файл + /// Current log file /// private string _currentLogFile; /// - /// Поток для вывода в файл + /// Stream to output to file /// private Stream _writer; /// - /// Лок на пересоздание файла + /// Lock on re-create file /// private readonly object _fileRecreating = new object(); @@ -85,7 +85,7 @@ namespace ZeroLevel.Services.Logging.Implementation var dir = Directory.CreateDirectory(_options.Folder); if (dir.Exists == false) { - throw new ArgumentException(string.Format("Can't create or found directory '{0}'", _options.Folder)); + throw new ArgumentException($"Can't create or found directory '{_options.Folder}'"); } } _obfuscator = new FastObfuscator(options.Key); @@ -97,7 +97,7 @@ namespace ZeroLevel.Services.Logging.Implementation #region Utils /// - /// Проверка имени лог-файла (изменяется при смене даты на следующий день) + /// Checking the name of the log file (changes when the date changes to the next day) /// private void RecreateLogFile() { @@ -122,7 +122,7 @@ namespace ZeroLevel.Services.Logging.Implementation } } /// - /// Закрытие текущего лога + /// Closing the current log /// private void CloseCurrentWriter() { @@ -165,9 +165,6 @@ namespace ZeroLevel.Services.Logging.Implementation #region IDisposable private bool _disposed = false; - /// - /// Освобождение рессурсов - /// public void Dispose() { Sheduller.Remove(_taskRename); diff --git a/ZeroLevel/Services/Logging/Implementation/TextFileLogger.cs b/ZeroLevel/Services/Logging/Implementation/TextFileLogger.cs index d26d3b5..ce277ef 100644 --- a/ZeroLevel/Services/Logging/Implementation/TextFileLogger.cs +++ b/ZeroLevel/Services/Logging/Implementation/TextFileLogger.cs @@ -26,15 +26,15 @@ namespace ZeroLevel.Services.Logging.Implementation internal long LimitFileSize { get; private set; } internal Encoding TextEncoding { get; private set; } /// - /// Удалять файлы старее чем (период устаревания) + /// Delete files older than (aging period) /// internal TimeSpan RemoveOlderThen { get; private set; } /// - /// Удалять устаревшие файлы + /// Delete outdate files /// internal bool RemoveOldFiles { get; private set; } /// - /// Архивировать файлы + /// Archive files /// internal bool ZipOldFiles { get; private set; } @@ -48,7 +48,7 @@ namespace ZeroLevel.Services.Logging.Implementation } /// - /// Включить автоматическое архивирование + /// Enable automatic archiving /// public TextFileLoggerOptions EnableAutoArchiving() { @@ -56,9 +56,9 @@ namespace ZeroLevel.Services.Logging.Implementation return this; } /// - /// Включить автоматическое удаление устаревших файлов + ///Enable automatic deletion of outdate files. /// - /// Возраст файла лога по достижении которого требуется удаление + /// The age of the log file at which removal is required public TextFileLoggerOptions EnableAutoCleaning(TimeSpan age) { this.RemoveOldFiles = true; @@ -98,21 +98,21 @@ namespace ZeroLevel.Services.Logging.Implementation var options = new TextFileLoggerOptions(). SetFolderPath(config.First(logPrefix)); - config.DoWithFirst(string.Format("{0}.backlog", logPrefix), backlog => + config.DoWithFirst($"{logPrefix}.backlog", backlog => { if (backlog > 0) { Log.Backlog(backlog); } }); - config.DoWithFirst(string.Format("{0}.archive", logPrefix), enable => + config.DoWithFirst($"{logPrefix}.archive", enable => { if (enable) { options.EnableAutoArchiving(); } }); - config.DoWithFirst(string.Format("{0}.sizeinkb", logPrefix), size => + config.DoWithFirst($"{logPrefix}.sizeinkb", size => { if (size >= 1) { @@ -120,7 +120,7 @@ namespace ZeroLevel.Services.Logging.Implementation } }); - config.DoWithFirst(string.Format("{0}.cleanolderdays", logPrefix), days => + config.DoWithFirst($"{logPrefix}.cleanolderdays", days => { if (days > 0) { @@ -140,15 +140,15 @@ namespace ZeroLevel.Services.Logging.Implementation private int _todayCountLogFiles = 0; /// - /// Текущий лог-файл + /// Current log file /// private string _currentLogFile; /// - /// Поток для вывода в файл + /// Stream to output to file /// private TextWriter _writer; /// - /// Лок на пересоздание файла + /// Lock on re-create file /// private readonly object _fileRecreating = new object(); @@ -160,9 +160,8 @@ namespace ZeroLevel.Services.Logging.Implementation #region Ctors /// - /// Конструктор с указанием каталога для записи лог-файлов, кодировка задается по умолчанию как Unicode + /// Constructor indicating the directory for recording log files, the encoding is set to Unicode by default. /// - /// public TextFileLogger(TextFileLoggerOptions options) { _options = options.Commit(); @@ -171,12 +170,11 @@ namespace ZeroLevel.Services.Logging.Implementation var dir = Directory.CreateDirectory(_options.Folder); if (dir.Exists == false) { - throw new ArgumentException(string.Format("Can't create or found directory '{0}'", _options.Folder)); + throw new ArgumentException($"Can't create or found directory '{_options.Folder}'"); } } RecreateLogFile(); - // Задачи обслуживания - // Пересоздание лог-файла при достижении размера больше указанного + // Maintenance tasks if (_options.LimitFileSize > 0) { _taskKeys.Add(Sheduller.RemindEvery(TimeSpan.FromSeconds(20), CheckRecreateFileLogByOversize)); @@ -212,7 +210,7 @@ namespace ZeroLevel.Services.Logging.Implementation } /// - /// Закрытие текущего лога + /// Closing the current log /// private void CloseCurrentWriter() { @@ -264,7 +262,7 @@ namespace ZeroLevel.Services.Logging.Implementation fi = null; } /// - /// Проверка имени лог-файла (изменяется при смене даты на следующий день) + /// Checking the name of the log file (changes when the date changes to the next day) /// private void RecreateLogFile() { @@ -296,7 +294,7 @@ namespace ZeroLevel.Services.Logging.Implementation { if (null != filePath && File.Exists(filePath) && _options.ZipOldFiles) { - using (var stream = new FileStream(string.Format("{0}.{1}", filePath, "zip"), FileMode.Create)) + using (var stream = new FileStream($"{filePath}.zip", FileMode.Create)) { using (var zipStream = new GZipStream(stream, CompressionLevel.Optimal, false)) { @@ -344,9 +342,6 @@ namespace ZeroLevel.Services.Logging.Implementation #region IDisposable private bool _disposed = false; - /// - /// Освобождение рессурсов - /// public void Dispose() { foreach (var tk in _taskKeys) @@ -366,18 +361,13 @@ namespace ZeroLevel.Services.Logging.Implementation { #region Fields /// - /// Поток для вывода в файл + /// Stream to output to file /// private TextWriter _writer; public static readonly Encoding DEFAULT_ENCODING = Encoding.UTF8; #endregion #region Ctors - - /// - /// Конструктор с указанием каталога для записи лог-файлов, кодировка задается по умолчанию как Unicode - /// - /// public FileLogger(string path) { CreateLogFile(PreparePath(path)); @@ -391,7 +381,7 @@ namespace ZeroLevel.Services.Logging.Implementation { Directory.CreateDirectory(path); FSUtils.SetupFolderPermission(path, - string.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName), + $"{Environment.UserDomainName}\\{Environment.UserName}", FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify, AccessControlType.Allow); } @@ -409,7 +399,7 @@ namespace ZeroLevel.Services.Logging.Implementation } /// - /// Закрытие текущего лога + /// Closing the current log /// private void CloseCurrentWriter() { @@ -464,9 +454,6 @@ namespace ZeroLevel.Services.Logging.Implementation #region IDisposable private bool _disposed = false; - /// - /// Освобождение рессурсов - /// public void Dispose() { if (false == _disposed) diff --git a/ZeroLevel/Services/Logging/Log.cs b/ZeroLevel/Services/Logging/Log.cs index 1c6f363..b9fa044 100644 --- a/ZeroLevel/Services/Logging/Log.cs +++ b/ZeroLevel/Services/Logging/Log.cs @@ -36,56 +36,56 @@ namespace ZeroLevel _router.Write(LogLevel.Raw, FormatMessage(line, args)); } /// - /// Сообщение + /// Info message /// public static void Info(string line, params object[] args) { _router.Write(LogLevel.Info, FormatMessage(line, args)); } /// - /// Предупреждение + /// Warning message /// public static void Warning(string line, params object[] args) { _router.Write(LogLevel.Warning, FormatMessage(line, args)); } /// - /// Ошибка + /// Error message /// public static void Error(string line, params object[] args) { _router.Write(LogLevel.Error, FormatMessage(line, args)); } /// - /// Ошибка + /// Error message /// public static void Error(Exception ex, string line, params object[] args) { _router.Write(LogLevel.Error, FormatMessage(line, args) + "\r\n" + ex.ToString()); } /// - /// Фатальный сбой + /// Fatal crash /// public static void Fatal(string line, params object[] args) { _router.Write(LogLevel.Fatal, FormatMessage(line, args)); } /// - /// Фатальный сбой + /// Fatal message (mean stop app after crash) /// public static void Fatal(Exception ex, string line, params object[] args) { _router.Write(LogLevel.Fatal, FormatMessage(line, args) + "\r\n" + ex.ToString()); } /// - /// Отладочная информация + /// Debug message /// public static void Debug(string line, params object[] args) { _router.Write(LogLevel.Debug, FormatMessage(line, args)); } /// - /// Низкоуровневая отладолчная информация + /// Low-level debug message /// public static void Verbose(string line, params object[] args) { @@ -94,47 +94,33 @@ namespace ZeroLevel /// - /// Сообщение + /// System message /// public static void SystemInfo(string line, params object[] args) { _router.Write(LogLevel.SystemInfo, FormatMessage(line, args)); } /// - /// Предупреждение + /// System warning /// public static void SystemWarning(string line, params object[] args) { _router.Write(LogLevel.SystemWarning, FormatMessage(line, args)); } /// - /// Ошибка + /// System error /// public static void SystemError(string line, params object[] args) { _router.Write(LogLevel.SystemError, FormatMessage(line, args)); } /// - /// Ошибка + /// System error /// public static void SystemError(Exception ex, string line, params object[] args) { _router.Write(LogLevel.SystemError, FormatMessage(line, args) + "\r\n" + ex.ToString()); } - /// - /// Фатальный сбой - /// - public static void SystemFatal(string line, params object[] args) - { - _router.Write(LogLevel.SystemFatal, FormatMessage(line, args)); - } - /// - /// Фатальный сбой - /// - public static void SystemFatal(Exception ex, string line, params object[] args) - { - _router.Write(LogLevel.SystemFatal, FormatMessage(line, args) + "\r\n" + ex.ToString()); - } #endregion #region Register loggers @@ -217,7 +203,7 @@ namespace ZeroLevel } } /// - /// Установка максимального количества сообщений в очереди + /// Set mam count log-messages in queue /// public static void Backlog(long backlog) { diff --git a/ZeroLevel/Services/Logging/LogLevel.cs b/ZeroLevel/Services/Logging/LogLevel.cs index f908ff8..37c3317 100644 --- a/ZeroLevel/Services/Logging/LogLevel.cs +++ b/ZeroLevel/Services/Logging/LogLevel.cs @@ -3,63 +3,62 @@ namespace ZeroLevel.Services.Logging { /// - /// Перечисление, содержит возможные типы сообщений, для записи в лог + /// Enum contains possible types of messages to write to the log /// [Flags] public enum LogLevel : int { None = 0, /// - /// Сообщение + /// Message /// Info = 1 << 0, /// - /// Предупреждение о возможной неполадке + /// Warning /// Warning = 1 << 1, /// - /// Ошибка в выполнении (некритичная) + /// Error /// Error = 1 << 2, /// - /// Ошибка приводящая к аварийному завершению программы + /// Fatal /// Fatal = 1 << 3, /// - /// Отладочная информация + /// Debug /// Debug = 1 << 4, /// - /// Низкоуровневое логирование + /// LowLevel Debug /// Verbose = 1 << 5, /// - /// Стандартный уровень логирования, сообщения, предупреждения, ошибки и падения + /// Info | Warning | Error | Fatal /// Standart = Info | Warning | Error | Fatal, /// - /// Вывод сообщения как есть, без даты и уровня логирования + /// Message output as is, without date and logging level /// Raw = 1 << 6, /// - /// Запиcь проблем, предупреждения, ошибки, сбои + /// Error | Fatal | Warning /// Problem = Error | Fatal | Warning, /// - /// Запись всех стандартных уровней, не включая отладочные + /// Info | Problem | Raw /// All = Info | Problem | Raw, /// - /// Все сообщения, включая отладочные и низкоуровневые + /// All | Verbose | Debug /// FullDebug = All | Verbose | Debug, SystemInfo = 1 << 6, SystemWarning = 1 << 7, SystemError = 1 << 8, - SystemFatal = 1 << 9, - System = SystemInfo | SystemError | SystemWarning | SystemFatal, + System = SystemInfo | SystemError | SystemWarning, FullStandart = Standart | System } diff --git a/ZeroLevel/Services/Logging/LogLevelNameMapping.cs b/ZeroLevel/Services/Logging/LogLevelNameMapping.cs index 332bc7a..837640a 100644 --- a/ZeroLevel/Services/Logging/LogLevelNameMapping.cs +++ b/ZeroLevel/Services/Logging/LogLevelNameMapping.cs @@ -16,8 +16,7 @@ namespace ZeroLevel.Services.Logging { LogLevel.SystemInfo, "SYSINF"}, { LogLevel.SystemError, "SYSERR"}, - { LogLevel.SystemWarning, "SYSWRN"}, - { LogLevel.SystemFatal, "SYSFLT"} + { LogLevel.SystemWarning, "SYSWRN"} }; private static readonly Dictionary _full = new Dictionary { @@ -31,8 +30,7 @@ namespace ZeroLevel.Services.Logging { LogLevel.SystemInfo, " system info"}, { LogLevel.SystemError, " system error"}, - { LogLevel.SystemWarning, " systm warning"}, - { LogLevel.SystemFatal, " system fatal"} + { LogLevel.SystemWarning, " systm warning"} }; public static string CompactName(LogLevel level) { return _compact[level]; } diff --git a/ZeroLevel/Services/Trees/ItemFieldToTreeConverter.cs b/ZeroLevel/Services/Trees/ItemFieldToTreeConverter.cs deleted file mode 100644 index 32aa8d7..0000000 --- a/ZeroLevel/Services/Trees/ItemFieldToTreeConverter.cs +++ /dev/null @@ -1,304 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZeroLevel.Services.Collections; - -namespace ZeroLevel.Services.Trees -{ - /// - /// Выполняет преобразование набора элементов в дерево (в набор ветвей) - /// - /// Тип элемента - /// Тип связующих компонентов элемента - public class ItemFieldToTreeConverter - { - #region Inner classes - private struct BranchTestResult - { - public bool HasInteraction; - public NodeBranch NewBranch; - } - - private struct Node - { - public T Value; - public TKey In; - public TKey Out; - - internal Node Clone() - { - return new Node - { - In = this.In, - Out = this.Out, - Value = this.Value - }; - } - - public bool Eq(Node other, Func comparer, Func key_comparer) - { - if (ReferenceEquals(this, other)) - return true; - return comparer(this.Value, other.Value) && - key_comparer(this.In, other.In) && - key_comparer(this.Out, other.Out); - } - - public override int GetHashCode() - { - return this.Value?.GetHashCode() ?? 0 ^ this.In.GetHashCode() ^ this.Out.GetHashCode(); - } - } - - private class NodeBranch - { - private List _nodes = new List(); - private readonly Func _key_comparer; - private readonly Func _comparer; - public IEnumerable Nodes - { - get - { - return _nodes; - } - } - - public NodeBranch(Node first, Func comparer, Func key_comparer) - { - _nodes.Add(first); - _key_comparer = key_comparer; - _comparer = comparer; - } - - public NodeBranch(IEnumerable nodes, Func comparer, Func key_comparer) - { - _nodes.AddRange(nodes); - _key_comparer = key_comparer; - _comparer = comparer; - } - - public List Extract() - { - return _nodes.Select(n => n.Value).ToList(); - } - - public BranchTestResult Test(Node node) - { - var result = new BranchTestResult { HasInteraction = false, NewBranch = null }; - if (_key_comparer(_nodes.Last().Out, node.In)) - { - _nodes.Add(node); - result.HasInteraction = true; - } - else if (_key_comparer(_nodes.First().In, node.Out)) - { - _nodes.Insert(0, node); - result.HasInteraction = true; - } - else - { - for (int i = 0; i < _nodes.Count; i++) - { - var current = _nodes[i]; - if (_key_comparer(current.Out, node.In)) - { - var list = _nodes.Take(i + 1).ToList(); - list.Add(node); - result.NewBranch = new NodeBranch(list, _comparer, _key_comparer); - result.HasInteraction = true; - break; - } - else if (_key_comparer(current.In, node.Out)) - { - var list = _nodes.Skip(i).ToList(); - list.Insert(0, node); - result.NewBranch = new NodeBranch(list, _comparer, _key_comparer); - result.HasInteraction = true; - break; - } - } - } - return result; - } - /// - /// Проверка возможности объединения с другой ветвью, если текущая является ее началом или продолжением - /// - public bool TryJoin(NodeBranch other) - { - if (other == null) - { - return false; - } - if (this._nodes.First().Eq(other._nodes.Last(), _comparer ,_key_comparer)) - { - this._nodes = other._nodes.Union(this._nodes).ToList(); - return true; - } - else if (this._nodes.Last().Eq(other._nodes.First(), _comparer, _key_comparer)) - { - this._nodes = this._nodes.Union(other._nodes).ToList(); - return true; - } - return false; - } - - public override bool Equals(object obj) - { - return this.Equals(obj as NodeBranch); - } - - public override int GetHashCode() - { - return this._nodes.GetEnumHashCode(); - } - - public bool Equals(NodeBranch other) - { - if (other == null) - return false; - if (ReferenceEquals(this, other)) - return true; - - return this._nodes.OrderingEquals(other._nodes); - } - } - #endregion - - private readonly Func _inKeyExtractor; - private readonly Func _outKeyExtractor; - private readonly Func _comparer; - private readonly Func _key_comparer; - /// - /// Конструктор - /// - /// Экстрактор входной связи элемента - /// Экстрактор исходящей связи элемента - public ItemFieldToTreeConverter(Func inKeyExtractor, - Func outKeyExtractor, - Func comparer = null, - Func key_comparer = null) - { - if (inKeyExtractor == null) - { - throw new ArgumentNullException(nameof(inKeyExtractor)); - } - if (outKeyExtractor == null) - { - throw new ArgumentNullException(nameof(outKeyExtractor)); - } - _inKeyExtractor = inKeyExtractor; - _outKeyExtractor = outKeyExtractor; - _comparer = comparer; - _key_comparer = key_comparer ?? new Func((k1, k2) => - { - if (k1 == null && k2 == null) return true; - if (k1 == null) return false; - if (k2 == null) return false; - return k1.Equals(k2); - }); - } - /// - /// Преобразование набора элементов к набору ветвей - /// - public IEnumerable> Convert(IEnumerable entries) - { - if (entries == null || entries.Any() == false) - { - return Enumerable.Empty>(); - } - var iterator = new SparseIterator(entries); - var result = new List(); - if (iterator.MoveNext() != -1) - { - result.Add(new NodeBranch(new Node - { - Value = iterator.Current, - In = _inKeyExtractor(iterator.Current), - Out = _outKeyExtractor(iterator.Current) - }, _comparer, _key_comparer)); - iterator.Exclude(); - } - else - { - return Enumerable.Empty>(); - } - int index; - var cachee = new Dictionary(); - while ((index = iterator.MoveNext()) != -1) - { - if (cachee.ContainsKey(index) == false) - { - cachee.Add(index, new Node - { - Value = iterator.Current, - In = _inKeyExtractor(iterator.Current), - Out = _outKeyExtractor(iterator.Current) - }); - } - var node = cachee[index]; - bool included = false; - var include = new List(); - foreach (var branch in result) - { - var tr = branch.Test(node); - if (tr.HasInteraction) - { - included = true; - if (tr.NewBranch != null) - { - include.Add(tr.NewBranch); - } - } - } - if (included == false) - { - result.Add(new NodeBranch(node, _comparer, _key_comparer)); - } - iterator.Exclude(); - if (include.Count > 0) result.AddRange(include); - } - // Проверить, если одна ветка является началом, или продолжением другой, выполнить склейки - for (int i = 0; i < result.Count - 1; i++) - { - var left = result[i]; - for (int j = i + 1; j < result.Count; j++) - { - var right = result[j]; - if (IsNodeBrunchEquals(left, right) || left.TryJoin(right)) - { - result.RemoveAt(j); j--; - } - } - } - return result.Select(e => e.Extract()); - } - - private bool IsNodeBrunchEquals(NodeBranch first, NodeBranch second) - { - if (first == null && second == null) - return true; - if (first == null) - return false; - if (second == null) - return false; - if (_comparer == null) - return first.Equals(second); - if (ReferenceEquals(first, second)) - return true; - - var f_arr = first.Nodes.ToArray(); - var s_arr = second.Nodes.ToArray(); - if (f_arr.Length != s_arr.Length) - return false; - for (int i = 0; i < f_arr.Length; i++) - { - var fi = f_arr[i]; - var si = s_arr[i]; - if (_key_comparer(fi.In, si.In) == false) return false; - if (_key_comparer(fi.Out, si.Out) == false) return false; - if (_comparer(fi.Value, si.Value) == false) return false; - } - return true; - } - } -} diff --git a/ZeroLevel/ZeroLevel.csproj b/ZeroLevel/ZeroLevel.csproj index 20beaad..d392b22 100644 --- a/ZeroLevel/ZeroLevel.csproj +++ b/ZeroLevel/ZeroLevel.csproj @@ -86,7 +86,6 @@ - @@ -95,12 +94,10 @@ - - @@ -137,7 +134,7 @@ - + @@ -365,7 +362,6 @@ - diff --git a/ZeroLevel/obj/Debug/ZeroLevel.csproj.CoreCompileInputs.cache b/ZeroLevel/obj/Debug/ZeroLevel.csproj.CoreCompileInputs.cache index e04f251..463c314 100644 --- a/ZeroLevel/obj/Debug/ZeroLevel.csproj.CoreCompileInputs.cache +++ b/ZeroLevel/obj/Debug/ZeroLevel.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -c7012002005514f37ffc568f2998758c453405e9 +3af5ac7a6b742028005a8a0757e8f6fbb4fd20fa diff --git a/ZeroLevel/obj/Debug/ZeroLevel.csprojAssemblyReference.cache b/ZeroLevel/obj/Debug/ZeroLevel.csprojAssemblyReference.cache index f96a474..55850f9 100644 Binary files a/ZeroLevel/obj/Debug/ZeroLevel.csprojAssemblyReference.cache and b/ZeroLevel/obj/Debug/ZeroLevel.csprojAssemblyReference.cache differ