diff --git a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache b/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache index ffd6fd9..7a6e9ee 100644 --- a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache +++ b/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -4f0bbfe8ac44b56784f7eeaa3cdef96609d6b97e +02ab5562f7a9f633d41e073aff759527ff59696c diff --git a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache b/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache index 9b98d20..117c263 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 104314d..d40012b 100644 --- a/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csproj.CoreCompileInputs.cache +++ b/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -48781ba1f58e845d50aedda0cbff5881dfe0563f +1a68033c72e3e719a45c8165f48f4effb88b5e68 diff --git a/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csprojAssemblyReference.cache b/ZeroLevel.Microservices/obj/Debug/ZeroLevel.Microservices.csprojAssemblyReference.cache index 3d9d0c1..63d7bd7 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/Models/InvokeResult.cs b/ZeroLevel/Models/InvokeResult.cs index d66280a..f0cdac0 100644 --- a/ZeroLevel/Models/InvokeResult.cs +++ b/ZeroLevel/Models/InvokeResult.cs @@ -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/Config/Configuration.cs b/ZeroLevel/Services/Config/Configuration.cs index afa421e..53aeaa8 100644 --- a/ZeroLevel/Services/Config/Configuration.cs +++ b/ZeroLevel/Services/Config/Configuration.cs @@ -83,7 +83,7 @@ namespace ZeroLevel IConfiguration result; if (false == _cachee.TryGetValue(name, out result)) { - throw new KeyNotFoundException(string.Format("Not found configuration '{0}'", name)); + throw new KeyNotFoundException("Not found configuration '{name}'"); } return result; } @@ -93,7 +93,7 @@ namespace ZeroLevel IConfigurationSet result; if (false == _setCachee.TryGetValue(name, out result)) { - throw new KeyNotFoundException(string.Format("Not found configuration set '{0}'", name)); + throw new KeyNotFoundException("Not found configuration set '{name}'"); } return result; } diff --git a/ZeroLevel/Services/Config/Implementation/AppWebConfigReader.cs b/ZeroLevel/Services/Config/Implementation/AppWebConfigReader.cs index 04bc4bd..981a0ba 100644 --- a/ZeroLevel/Services/Config/Implementation/AppWebConfigReader.cs +++ b/ZeroLevel/Services/Config/Implementation/AppWebConfigReader.cs @@ -14,7 +14,7 @@ namespace ZeroLevel.Services.Config.Implementation { if (configFilePath == null) { - var appConfig = Path.Combine(Configuration.BaseDirectory, string.Format("{0}.config", System.AppDomain.CurrentDomain.FriendlyName)); + var appConfig = Path.Combine(Configuration.BaseDirectory, $"{System.AppDomain.CurrentDomain.FriendlyName}.config"); if (File.Exists(appConfig)) { _configFilePath = appConfig; diff --git a/ZeroLevel/Services/Config/Implementation/IniFileReader.cs b/ZeroLevel/Services/Config/Implementation/IniFileReader.cs index e8386ff..5f2f889 100644 --- a/ZeroLevel/Services/Config/Implementation/IniFileReader.cs +++ b/ZeroLevel/Services/Config/Implementation/IniFileReader.cs @@ -63,7 +63,7 @@ namespace ZeroLevel.Services.Config.Implementation { if (!string.IsNullOrEmpty(sectionName)) { - result.Append(string.Format("{0}.{1}", sectionName, key), value); + result.Append($"{sectionName}.{key}", value); } else { diff --git a/ZeroLevel/Services/DOM/DSL/Contexts/TBlockContext.cs b/ZeroLevel/Services/DOM/DSL/Contexts/TBlockContext.cs index a23d7f0..a05d59d 100644 --- a/ZeroLevel/Services/DOM/DSL/Contexts/TBlockContext.cs +++ b/ZeroLevel/Services/DOM/DSL/Contexts/TBlockContext.cs @@ -32,7 +32,7 @@ namespace DOM.DSL.Contexts { reader.Move(); var name = reader.ReadIdentity(); - if (name.Equals(string.Format("end{0}", _name))) + if (name.Equals($"end{_name}")) { reader.Move(name.Length); return; @@ -64,7 +64,7 @@ namespace DOM.DSL.Contexts { reader.Move(); var name = reader.ReadIdentity(); - if (name.Equals(string.Format("end{0}", _name))) + if (name.Equals($"end{_name}")) { reader.Move(name.Length); return; @@ -106,7 +106,7 @@ namespace DOM.DSL.Contexts if (offset == -1) return; reader.Move(offset + 1); var name = reader.ReadIdentity(); - if (name.Equals(string.Format("end{0}", _name))) + if (name.Equals($"end{_name}")) { reader.Move(name.Length); return; diff --git a/ZeroLevel/Services/DOM/Services/ContentElementSerializer.cs b/ZeroLevel/Services/DOM/Services/ContentElementSerializer.cs index 1cc26b5..2cf68ae 100644 --- a/ZeroLevel/Services/DOM/Services/ContentElementSerializer.cs +++ b/ZeroLevel/Services/DOM/Services/ContentElementSerializer.cs @@ -50,7 +50,7 @@ namespace DOM.Services case ContentElementType.Form: return new FormContent(reader); } - throw new InvalidCastException(string.Format("Uncknown element type: {0}", type)); + throw new InvalidCastException($"Uncknown element type: {type}"); } public static List ReadCollection(IBinaryReader reader) diff --git a/ZeroLevel/Services/IdGenerator.cs b/ZeroLevel/Services/IdGenerator.cs index 060ae7f..b17abcb 100644 --- a/ZeroLevel/Services/IdGenerator.cs +++ b/ZeroLevel/Services/IdGenerator.cs @@ -5,12 +5,12 @@ using System.Threading; namespace ZeroLevel.Services { /// - /// Предоставляет различные варианты генерации идентификаторов + /// Provides various options for generating identifiers /// public static class IdGenerator { /// - /// Возвращает функцию для получения последовательных значений int64 + /// Returns a function to get consecutive int64 values. /// public static Func IncreasingSequenceIdGenerator() { @@ -18,7 +18,7 @@ namespace ZeroLevel.Services return new Func(() => Interlocked.Increment(ref id)); } /// - /// Создает Base64 хэш от указанного даты/времени + /// Creates a base64 hash from the specified datetime /// public static string HashFromDateTime(DateTime date) { @@ -29,35 +29,35 @@ namespace ZeroLevel.Services .TrimEnd('='); } /// - /// Создает Base64 хэш от текущего даты/времени + /// Creates a base64 hash from the current datetime /// public static string HashFromCurrentDateTime() { return HashFromDateTime(DateTime.Now); } /// - /// Возвращает хэш в виде строки от 32-хбитного значения хэша указанного даты/времени + /// Returns a hash as a string from the 32-bit hash value of the specified datetime /// public static string ShortHashFromDateTime(DateTime date) { return date.ToString(CultureInfo.InvariantCulture).GetHashCode().ToString("x"); } /// - /// Возвращает хэш в виде строки от 32-хбитного значения хэша текущего даты/времени + /// Returns a hash as a string from the 32-bit hash value of the current datetime /// public static string ShortHashFromCurrentDateTime() { return DateTime.Now.ToString(CultureInfo.InvariantCulture).GetHashCode().ToString("x"); } /// - /// Создает временную отметку из текущей даты/времени + /// Creates a timestamp from current datetime /// public static string CreateTimestamp() { return DateTime.Now.ToString("yyyyMMddHHmmssFFF"); } /// - /// Создает временную отметку из указанной даты/времени + /// Creates a timestamp from a specified datetime /// public static string CreateTimestamp(DateTime date) { diff --git a/ZeroLevel/Services/Network/Exceptions/NoConnectionException.cs b/ZeroLevel/Services/Network/Exceptions/NoConnectionException.cs deleted file mode 100644 index 46540b9..0000000 --- a/ZeroLevel/Services/Network/Exceptions/NoConnectionException.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace ZeroLevel.Services.Network.Exceptions -{ - public class NoConnectionException - : Exception - { - } -} diff --git a/ZeroLevel/Services/Network/Models/ExchangeAttributes.cs b/ZeroLevel/Services/Network/Models/ExchangeAttributes.cs index 5bdc5f0..182506c 100644 --- a/ZeroLevel/Services/Network/Models/ExchangeAttributes.cs +++ b/ZeroLevel/Services/Network/Models/ExchangeAttributes.cs @@ -4,15 +4,15 @@ namespace ZeroLevel.Network.Microservices { public abstract class ExchangeAttribute : Attribute { } /// - /// Отмечает метод который является обработчиком сообщений по умолчанию + /// Marks the method that is the default message handler /// public sealed class ExchangeMainHandlerAttribute : ExchangeAttribute { } /// - /// Отмечает метод который является обработчиком запросов по умолчанию + /// Marks the method that is the default message handler /// public sealed class ExchangeMainReplierAttribute : ExchangeAttribute { } /// - /// Отмечает метод-обработчик сообщений для inbox'а с указанным именем + /// Marks a message handler method for an inbox with the specified name. /// public sealed class ExchangeHandlerAttribute : ExchangeAttribute { @@ -24,7 +24,7 @@ namespace ZeroLevel.Network.Microservices } } /// - /// Отмечает метод-обработчик запросов для inbox'а с указанным именем + /// Marks a message handler method for an inbox with the specified name. /// public sealed class ExchangeReplierAttribute : ExchangeAttribute { @@ -36,11 +36,11 @@ namespace ZeroLevel.Network.Microservices } } /// - /// Отмечает метод-обработчик сообщений для inbox'а с указанным именем + /// Marks a message handler method for an inbox with the specified name. /// public sealed class ExchangeMainReplierWithoutArgAttribute : ExchangeAttribute { } /// - /// Отмечает метод-обработчик запросов для inbox'а с указанным именем + /// Marks a message handler method for an inbox with the specified name. /// public sealed class ExchangeReplierWithoutArgAttribute : ExchangeAttribute { diff --git a/ZeroLevel/Services/Network/Models/MicroserviceInfo.cs b/ZeroLevel/Services/Network/Models/MicroserviceInfo.cs index 54a8ad3..0ed6118 100644 --- a/ZeroLevel/Services/Network/Models/MicroserviceInfo.cs +++ b/ZeroLevel/Services/Network/Models/MicroserviceInfo.cs @@ -12,35 +12,33 @@ namespace ZeroLevel.Network.Microservices public const string DEFAULT_TYPE_NAME = "__service_default_type__"; /// - /// Ключ сервиса, должен быть уникален в рамках бизнес функционала - /// т.е. с одинаковым ключом могут работать только копии сервиса, для горизонтальной балансировки + /// Service key, must be unique within the business functionality. + /// two services with same key will be horizontally balanced /// [DataMember] public string ServiceKey { get; set; } /// - /// Группа, для фильтрации, в качетсве группы можно определять сервисы работающие в одном домене, - /// например сервисы обрабатывющие новости в одной группе, сервисы по котировкам в другой + /// The group can determine the services working in the same domain /// [DataMember] public string ServiceGroup { get; set; } = DEFAULT_GROUP_NAME; /// - /// Тип сервиса, для фильтрации, определяет принадлежность к подгруппе, например сервисы для доставки информации, - /// или сервисы-адаптеры и т.д. + /// The type of service, for filtering, determines membership in a subgroup. /// [DataMember] public string ServiceType { get; set; } = DEFAULT_TYPE_NAME; /// - /// Протокол по которому разрешен доступ к API сервиса + /// Protocol on which access to the service API is allowed /// [DataMember] public string Protocol { get; set; } /// - /// Точка подключения, адрес + /// Connection point, address /// [DataMember] public string Endpoint { get; set; } /// - /// Версия сервиса + /// Service version /// [DataMember] public string Version { get; set; } diff --git a/ZeroLevel/Services/Network/Models/ServiceEndpointInfo.cs b/ZeroLevel/Services/Network/Models/ServiceEndpointInfo.cs index ddde80f..0d71fda 100644 --- a/ZeroLevel/Services/Network/Models/ServiceEndpointInfo.cs +++ b/ZeroLevel/Services/Network/Models/ServiceEndpointInfo.cs @@ -3,7 +3,7 @@ namespace ZeroLevel.Network.Microservices { /// - /// Точка подключения + /// Endpoint /// public class ServiceEndpointInfo : IEquatable diff --git a/ZeroLevel/Services/Network/Models/ServiceEndpointsInfo.cs b/ZeroLevel/Services/Network/Models/ServiceEndpointsInfo.cs index 558b551..25a0d31 100644 --- a/ZeroLevel/Services/Network/Models/ServiceEndpointsInfo.cs +++ b/ZeroLevel/Services/Network/Models/ServiceEndpointsInfo.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; namespace ZeroLevel.Network.Microservices { /// - /// Информация о точках подключения для сервиса + /// Information about service connection points /// public class ServiceEndpointsInfo : IEquatable diff --git a/ZeroLevel/Services/Network/Services/ExRouter.cs b/ZeroLevel/Services/Network/Services/ExRouter.cs index d1c8617..9cd148d 100644 --- a/ZeroLevel/Services/Network/Services/ExRouter.cs +++ b/ZeroLevel/Services/Network/Services/ExRouter.cs @@ -14,10 +14,8 @@ namespace ZeroLevel.Services.Network.Services private sealed class MRInvoker { /// - /// Создает скомпилированное выражение для быстрого вызова метода, возвращает идентификатор выражения и делегат для вызова + /// Creates a compiled expression for a quick method call, returns the identifier of the expression and a delegate for the call. /// - /// Оборачиваемый метод - /// Кортеж с идентификатором выражения и делегатом private static Invoker CreateCompiledExpression(MethodInfo method) { var targetArg = Expression.Parameter(typeof(object)); // Цель на которой происходит вызов @@ -36,11 +34,6 @@ namespace ZeroLevel.Services.Network.Services body = Expression.Convert(body, typeof(object)); return Expression.Lambda(body, targetArg, argsArg).Compile(); } - /// - /// Оборачивает вызов делегата - /// - /// Оборачиваемый делегат - /// Кортеж с идентификатором выражения и делегатом private static Invoker CreateCompiledExpression(Delegate handler) { return CreateCompiledExpression(handler.GetMethodInfo()); @@ -127,7 +120,7 @@ namespace ZeroLevel.Services.Network.Services } else { - throw new Exception(string.Format("[SocketExchangeServer] Inbox {0} already exists", inbox)); + throw new Exception($"[SocketExchangeServer] Inbox {inbox} already exists"); } } @@ -139,7 +132,7 @@ namespace ZeroLevel.Services.Network.Services } else { - throw new Exception(string.Format("[SocketExchangeServer] Inbox {0} already exists", inbox)); + throw new Exception($"[SocketExchangeServer] Inbox {inbox} already exists"); } } #endregion diff --git a/ZeroLevel/Services/Network/Services/ExService.cs b/ZeroLevel/Services/Network/Services/ExService.cs index 32a7230..f581d01 100644 --- a/ZeroLevel/Services/Network/Services/ExService.cs +++ b/ZeroLevel/Services/Network/Services/ExService.cs @@ -47,11 +47,11 @@ namespace ZeroLevel.Services.Network public IPEndPoint Endpoint => _server.Endpoint; /// - /// Регистрация обработчика входящих сообщений + /// Registering an Inbox Handler /// - /// Тип сообщения - /// Имя точки приема - /// Обработчик + /// Message type + /// Inbox name + /// Handler public void RegisterInbox(string inbox, Action handler) { _router.RegisterInbox(inbox, handler); @@ -61,13 +61,13 @@ namespace ZeroLevel.Services.Network _router.RegisterInbox(DEFAULT_MESSAGE_INBOX, handler); } /// - /// Регистрация метода отдающего ответ на входящий запрос + /// Registration method responding to an incoming request /// - /// Тип входного сообщения - /// Тип ответа - /// Транспортный протокол - /// Имя точки приема - /// Обработчик + /// Type of input message + /// Type of response + /// Protocol + /// Inbox name + /// Handler public void RegisterInbox(string inbox, Func handler) { _router.RegisterInbox(inbox, handler); @@ -77,12 +77,12 @@ namespace ZeroLevel.Services.Network _router.RegisterInbox(DEFAULT_REQUEST_INBOX, handler); } /// - /// Регистрация метода отдающего ответ на входящий запрос, не принимающего входящих данных + /// Registration of the method of responding to the incoming request, not receiving incoming data /// - /// Тип ответа - /// Транспортный протокол - /// Имя точки приема - /// Обработчик + /// Type of response + /// Protocol + /// Inbox name + /// Handler public void RegisterInbox(string inbox, Func handler) { _router.RegisterInbox(inbox, handler); diff --git a/ZeroLevel/Services/Network/Services/FrameParser.cs b/ZeroLevel/Services/Network/Services/FrameParser.cs index eef1297..9cd4b0c 100644 --- a/ZeroLevel/Services/Network/Services/FrameParser.cs +++ b/ZeroLevel/Services/Network/Services/FrameParser.cs @@ -48,7 +48,7 @@ namespace ZeroLevel.Services.Network offset = 0; if (Size == 0) { - // Как минимум 1 байт с контрольной суммой должен быть + // At least 1 byte with checksum must be Corrupted = true; } } @@ -135,7 +135,7 @@ namespace ZeroLevel.Services.Network { for (; start < length; start++) { - // Поиск начала заголовка пакета + // Search for the beginning of the package header if ((part[start] & ZBaseNetwork.PACKET_HEADER_START_BYTE) == ZBaseNetwork.PACKET_HEADER_START_BYTE) { _accum.Reset(); diff --git a/ZeroLevel/Services/Network/ZBaseNetwork.cs b/ZeroLevel/Services/Network/ZBaseNetwork.cs index bd49928..26a1dd9 100644 --- a/ZeroLevel/Services/Network/ZBaseNetwork.cs +++ b/ZeroLevel/Services/Network/ZBaseNetwork.cs @@ -11,32 +11,32 @@ namespace ZeroLevel.Services.Network protected const string DEFAULT_PING_INBOX = "__ping__"; protected const string DEFAULT_REQUEST_ERROR_INBOX = "__request_error__"; /// - /// Размер буфера для приема данных + /// Buffer size for receiving data /// protected const int DEFAULT_RECEIVE_BUFFER_SIZE = 4096; /// - /// Если в течение указанного периода не было сетевой активности, выслать пинг-реквест + /// If during the specified period there was no network activity, send a ping-request /// protected const long HEARTBEAT_PING_PERIOD_TICKS = 1500 * TimeSpan.TicksPerMillisecond; /// - /// Период проверки наличия соединения + /// Connection check period /// protected const int HEARTBEAT_UPDATE_PERIOD_MS = 7500; /// - /// Период выполнения запроса, после которого считать его неудачным + /// The period of the request, after which it is considered unsuccessful /// protected const long MAX_REQUEST_TIME_TICKS = 30000 * TimeSpan.TicksPerMillisecond; public const int MAX_REQUEST_TIME_MS = 30000; /// - /// Максимальный размер пакета данных для передачи (сериализованный размер фрейма) + /// Maximum size of data packet to transmit (serialized frame size) /// public const int MAX_FRAME_PAYLOAD_SIZE = 1024 * 1024 * 32; /// - /// Начальный байт заголовка пакета данных + /// Starting byte of the data packet header /// public const byte PACKET_HEADER_START_BYTE = 181; /// - /// Размер очереди сообщения для отправки + /// The size of the message queue to send /// public const int MAX_SEND_QUEUE_SIZE = 1024; diff --git a/ZeroLevel/Services/Network/ZSocketClient.cs b/ZeroLevel/Services/Network/ZSocketClient.cs index 6e6f379..7163661 100644 --- a/ZeroLevel/Services/Network/ZSocketClient.cs +++ b/ZeroLevel/Services/Network/ZSocketClient.cs @@ -5,7 +5,6 @@ using System.Net; using System.Net.Sockets; using System.Threading; using ZeroLevel.Services.Network.Contract; -using ZeroLevel.Services.Network.Exceptions; using ZeroLevel.Services.Network.Models; using ZeroLevel.Services.Pools; using ZeroLevel.Services.Serialization; diff --git a/ZeroLevel/Services/ObjectMapping/TypeMapper.cs b/ZeroLevel/Services/ObjectMapping/TypeMapper.cs index fb7e138..9277ea2 100644 --- a/ZeroLevel/Services/ObjectMapping/TypeMapper.cs +++ b/ZeroLevel/Services/ObjectMapping/TypeMapper.cs @@ -91,8 +91,7 @@ namespace ZeroLevel.Services.ObjectMapping var setter = this._fields[name].Setter; if (setter == null) { - throw new Exception(string.Format("{0} '{1}' has not setter", - this._fields[name].IsField ? "Field" : "Property", name)); + throw new Exception($"{(this._fields[name].IsField ? "Field" : "Property")} '{name}' has not setter"); } if (value == null) { @@ -116,12 +115,11 @@ namespace ZeroLevel.Services.ObjectMapping var getter = this._fields[name]?.Getter; if (getter == null) { - throw new Exception(string.Format("{0} '{1}' has not getter", - this._fields[name].IsField ? "Field" : "Property", name)); + throw new Exception($"{(this._fields[name].IsField ? "Field" : "Property")} '{name}' has not getter"); } return getter(instance); } - throw new KeyNotFoundException(string.Format("Not found field {0}", name)); + throw new KeyNotFoundException($"Not found field {name}"); } public T Get(object instance, string name) @@ -131,12 +129,11 @@ namespace ZeroLevel.Services.ObjectMapping var getter = this._fields[name]?.Getter; if (getter == null) { - throw new Exception(string.Format("{0} '{1}' has not getter", - this._fields[name].IsField ? "Field" : "Property", name)); + throw new Exception($"{(this._fields[name].IsField ? "Field" : "Property")} '{name}' has not getter"); } return (T)getter(instance); } - throw new KeyNotFoundException(string.Format("Not found field {0}", name)); + throw new KeyNotFoundException($"Not found field {name}"); } public object GetOrDefault(object instance, string name, object defaultValue) @@ -150,7 +147,7 @@ namespace ZeroLevel.Services.ObjectMapping } return getter(instance); } - throw new KeyNotFoundException(string.Format("Not found field {0}", name)); + throw new KeyNotFoundException($"Not found field {name}"); } public T GetOrDefault(object instance, string name, T defaultValue) @@ -164,7 +161,7 @@ namespace ZeroLevel.Services.ObjectMapping } return (T)getter(instance); } - throw new KeyNotFoundException(string.Format("Not found field {0}", name)); + throw new KeyNotFoundException($"Not found field {name}"); } #endregion diff --git a/ZeroLevel/Services/Queries/Builder/IQueryBuilder.cs b/ZeroLevel/Services/Queries/Builder/IQueryBuilder.cs index 4e59b41..c1b46dc 100644 --- a/ZeroLevel/Services/Queries/Builder/IQueryBuilder.cs +++ b/ZeroLevel/Services/Queries/Builder/IQueryBuilder.cs @@ -3,10 +3,10 @@ public interface IQueryBuilder { /// - /// Превращение абстрактного запроса в реальный, под конкретное хранилище + /// Turning an abstract query into a real one, for a specific repository /// - /// Абстрактный запрос - /// Запрос к хранилищу конкретного типа + /// Abstract query + /// Request to store a specific type IRealQuery Build(IQuery query); } } diff --git a/ZeroLevel/Services/Reflection/StringToTypeConverter.cs b/ZeroLevel/Services/Reflection/StringToTypeConverter.cs index ea10c8a..e49a28f 100644 --- a/ZeroLevel/Services/Reflection/StringToTypeConverter.cs +++ b/ZeroLevel/Services/Reflection/StringToTypeConverter.cs @@ -8,12 +8,8 @@ namespace ZeroLevel.Services.Reflection #region TypeHelpers /// - /// Преобразование строки в тип, если для типа есть соответствующий конвертер, при отсутствии конвертера возвращается - /// состояние по умолчанию для указанного типа + /// Сonverting a string to a type, if there is a corresponding converter for the type, in the absence of a converter, the default state for the specified type is returned /// - /// Строка - /// Тип к которому требуется привести значение в строке - /// Результат преобразования public static object TryConvert(string input, Type to) { try @@ -28,17 +24,14 @@ namespace ZeroLevel.Services.Reflection } /// - /// Создание значения по умолчанию для указанного типа + /// Creating default values for specified type /// - /// Тип - /// Значение по умолчанию private static object CreateDefaultState(Type type) { if (type.IsValueType) { return Activator.CreateInstance(type); } - return null; } diff --git a/ZeroLevel/Services/Reflection/TypeFastAccessMethodBuilderImpl.cs b/ZeroLevel/Services/Reflection/TypeFastAccessMethodBuilderImpl.cs index 4e8755d..b11977a 100644 --- a/ZeroLevel/Services/Reflection/TypeFastAccessMethodBuilderImpl.cs +++ b/ZeroLevel/Services/Reflection/TypeFastAccessMethodBuilderImpl.cs @@ -34,7 +34,7 @@ namespace ZeroLevel.Services.Reflection return (Func)lambda.Compile(); } /// - /// Создает быстрый сеттер для свойства + /// Creates a quick setter for a property /// public Action BuildSetter(PropertyInfo property) { @@ -53,7 +53,7 @@ namespace ZeroLevel.Services.Reflection return expr.Compile(); } /// - /// Создает быстрый сеттер для поля + /// Creates a quick setter for a field. /// public Action BuildSetter(FieldInfo field) { diff --git a/ZeroLevel/Services/Reflection/TypeHelpers.cs b/ZeroLevel/Services/Reflection/TypeHelpers.cs index d281af9..a47873d 100644 --- a/ZeroLevel/Services/Reflection/TypeHelpers.cs +++ b/ZeroLevel/Services/Reflection/TypeHelpers.cs @@ -9,113 +9,78 @@ using System.Runtime.Serialization; namespace ZeroLevel.Services.Reflection { /// - /// Набор методов для работы с типами объектов + /// A set of methods for working with object types /// public static class TypeHelpers { - /// - /// True если массив - /// public static bool IsArray(Type type) { return type.Return(t => t.IsArray, false); } - /// - /// True если структура - /// public static bool IsStruct(Type type) { return type.Return(t => t.IsValueType && !IsSimpleType(t), false); } - /// - /// True если класс - /// public static bool IsClass(Type type) { return type.Return(t => t.IsClass, false); } - /// - /// True если URI - /// public static bool IsUri(Type type) { return type.Return(t => (typeof(Uri).IsAssignableFrom(t)), false); } - /// - /// True если хэшсет - /// public static bool IsHashSet(Type type) { return type.Return(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(HashSet<>), false); } - - /// - /// True если строка - /// public static bool IsString(Type type) { return type.Return(t => t == typeof(string)); } - /// - /// True если базовый тип - date, decimal, string, или GUID - /// - public static bool IsSimpleType(Type type) - { - return type.Return(t => - { - if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) - { - t = Nullable.GetUnderlyingType(t); - } - return t.IsPrimitive - || t == typeof(DateTime) - || t == typeof(decimal) - || t == typeof(string) - || t == typeof(Guid) - || t == typeof(TimeSpan); - }, false); - } - /// - /// True если тип данных - /// public static bool IsRuntimeType(Type type) { return type.Return(t => (typeof(Type).IsAssignableFrom(t)), false); } - /// - /// True если IPEndPoint - /// public static bool IsIpEndPoint(Type type) { return type.Return(t => t == typeof(IPEndPoint), false); } - /// - /// True если DataSet - /// public static bool IsDataset(Type type) { return type.Return(t => t == typeof(DataSet), false); } - /// - /// True если DataTable - /// public static bool IsDataTable(Type type) { return type.Return(t => t == typeof(DataTable), false); } - /// - /// True если DataRow - /// public static bool IsDataRow(Type type) { return type.Return(t => t == typeof(DataRow), false); } - public static bool IsList(Type type) { return type.Return(t => t.GetInterfaces().Contains(typeof(IList)), false); } + /// + /// True if the base type is datetime, decimal, string, or GUID + /// + public static bool IsSimpleType(Type type) + { + return type.Return(t => + { + if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + t = Nullable.GetUnderlyingType(t); + } + return t.IsPrimitive + || t == typeof(DateTime) + || t == typeof(decimal) + || t == typeof(string) + || t == typeof(Guid) + || t == typeof(TimeSpan); + }, false); + } public static bool IsDictionary(Type type) { diff --git a/ZeroLevel/Services/Semantic/Contracts/ILexProvider.cs b/ZeroLevel/Services/Semantic/Contracts/ILexProvider.cs index 35c74ec..cfd9084 100644 --- a/ZeroLevel/Services/Semantic/Contracts/ILexProvider.cs +++ b/ZeroLevel/Services/Semantic/Contracts/ILexProvider.cs @@ -5,33 +5,33 @@ namespace ZeroLevel.Services.Semantic public interface ILexProvider { /// - /// Выделение токенов из текста как есть + /// Extract tokens from text as is /// - /// Список токенов + /// Spisok tokenov IEnumerable ExtractLexTokens(string text); /// - /// Выделение уникальных токенов из текста + /// Selecting unique tokens from text /// - /// Список токенов + /// Tokens IEnumerable ExtractUniqueLexTokens(string text); /// - /// Выделение уникальных токенов из текста с отбрасыванием стоп-слов + /// Allocation of unique tokens from text with drop of stop words /// - /// Список токенов + /// Tokens IEnumerable ExtractUniqueLexTokensWithoutStopWords(string text); /// - /// Поиск токенов в тексте соответствующих указанным словам (полнотекстовый поиск) + /// Search for tokens in the text corresponding to the specified words (full-text search) /// - /// Текст по которому выполняется поиск - /// Слова для поиска - /// Словарь, где ключ - слово, значение - список соответствующих ему найденных токенов + /// Search text + /// Search words + /// Dictionary, where key is a word, value is a list of matching tokens found for it IDictionary> SearchLexTokensByWords(string text, string[] words); /// - /// Поиск токенов в тексте соответствующих указанным фразам (полнотекстовый поиск) + /// Search for tokens in the text corresponding to the specified phrases (full-text search) /// - /// Текст по которому выполняется поиск - /// Фразы для поиска - /// Словарь, где ключ - фраза, значение - список соответствующих ему найденных массивов токенов + /// Search text + /// Search phrases + /// The dictionary, where the key is a phrase, a value is a list of token arrays corresponding to it IDictionary> SearchLexTokensByPhrases(string text, string[] phrases); } } diff --git a/ZeroLevel/Services/Semantic/Contracts/ILexer.cs b/ZeroLevel/Services/Semantic/Contracts/ILexer.cs index 99768e0..c7e874f 100644 --- a/ZeroLevel/Services/Semantic/Contracts/ILexer.cs +++ b/ZeroLevel/Services/Semantic/Contracts/ILexer.cs @@ -1,7 +1,7 @@ namespace ZeroLevel.Services.Semantic { /// - /// Выполняет преобразование слова к абстрактной основе слова(корень, стем, лемма и т.п.) + /// Performs word conversion to abstract word basis (root, stem, lemma, etc.) /// public interface ILexer { diff --git a/ZeroLevel/Services/Semantic/Contracts/LexToken.cs b/ZeroLevel/Services/Semantic/Contracts/LexToken.cs index ffc1750..e1b7bc9 100644 --- a/ZeroLevel/Services/Semantic/Contracts/LexToken.cs +++ b/ZeroLevel/Services/Semantic/Contracts/LexToken.cs @@ -32,7 +32,7 @@ namespace ZeroLevel.Services.Semantic { if ((object)this == (object)other) return true; - if (this == null) // и так бывает + if (this == null) throw new NullReferenceException(); if (other == null) return false; diff --git a/ZeroLevel/Services/Semantic/Contracts/README.txt b/ZeroLevel/Services/Semantic/Contracts/README.txt index 26f1b54..838377f 100644 --- a/ZeroLevel/Services/Semantic/Contracts/README.txt +++ b/ZeroLevel/Services/Semantic/Contracts/README.txt @@ -1,22 +1,22 @@ -Реализация основы для семантической работы с текстом. +The implementation of the basis for semantic work with the text. -LexProvider - реализует выделение токенов из текста, где под токеном понимается какое-либо приведение слова. -Например, токеном может являться непосредственно само слово, стем, лемма. +LexProvider - implements the selection of tokens from the text, where a token is any coercion of a word. +For example, a token can be directly the word itself, a system, a lemma. -В качестве реализации созданы две фабрики: +Two factories were created as an implementation: -SnowbolLexProviderFactory - возвращает провайдеры на основе стемминга 'Snowball' -JustWordLexProviderFactory - возвращает провайдер который принимает за токен непосредственно слово, без изменений (lower case) +SnowbolLexProviderFactory - returns providers based on stemming 'Snowball' +JustWordLexProviderFactory - returns a provider that takes the word itself for the token, no change (lower case) -Для реализации собственного провайдера потребуется создать класс на основе интерфейса ILexer и реализовать метод Lex, -в котором будет проведена необходимая нормализация слова в нужном семантическом контексте. +To implement your own provider, you need to create a class based on the ILexer interface and implement the Lex method, +in which the necessary normalization of the word in the necessary semantic context will be carried out. -Например: +For example: public class LemmaLexer: ILexer { - public string Lex(string word) { return Lemmatizer.Lemma(word); } +public string Lex (string word) {return Lemmatizer.Lemma (word); } } -После чего можно создать на его основе провайдер: +Then you can create a provider based on it: -var provider = new LexProvider(new LemmaLexer()); \ No newline at end of file +var provider = new LexProvider (new LemmaLexer ()); \ No newline at end of file diff --git a/ZeroLevel/Services/Semantic/Helpers/TextAnalizer.cs b/ZeroLevel/Services/Semantic/Helpers/TextAnalizer.cs index 9ab249b..1dc9aeb 100644 --- a/ZeroLevel/Services/Semantic/Helpers/TextAnalizer.cs +++ b/ZeroLevel/Services/Semantic/Helpers/TextAnalizer.cs @@ -11,10 +11,10 @@ namespace ZeroLevel.Implementation.Semantic.Helpers RegexOptions.Compiled | RegexOptions.IgnoreCase); /// - /// Выделение слов из текста + /// Highlighting words from text /// - /// Текст - /// Список слов + /// Text + /// Words public static IEnumerable ExtractWords(string text) { var result = new List(); @@ -27,30 +27,30 @@ namespace ZeroLevel.Implementation.Semantic.Helpers } /// - /// Выделение уникальных слов из текста + /// Highlighting unique words from text /// - /// Текст - /// Список уникальных слов + /// Text + /// List of unique words public static IEnumerable ExtractUniqueWords(string text) { return new HashSet(ExtractWords(text)); } /// - /// Выделение уникальных слов из текста без стоп слов + /// Highlighting unique words from text without stop words /// - /// Текст - /// Список уникальных слов без стоп слов + /// Text + /// List of unique words without stop words public static IEnumerable ExtractUniqueWordsWithoutStopWords(string text) { return new HashSet(ExtractUniqueWords(text).Where(w => StopWords.IsStopWord(w) == false)); } /// - /// Выделение токенов из текста + /// Extract tokens from text /// - /// Текст - /// Список токенов + /// Text + /// Tokens public static IEnumerable ExtractWordTokens(string text) { var result = new List(); @@ -63,20 +63,20 @@ namespace ZeroLevel.Implementation.Semantic.Helpers } /// - /// Выделение уникальных токенов из текста (первое вхождение) + /// Selection of unique tokens from the text (first entry) /// - /// Текст - /// Список уникальных токенов + /// Text + /// List of unique tokens public static IEnumerable ExtractUniqueWordTokens(string text) { return ExtractWordTokens(text).DistinctBy(t => t.Word); } /// - /// Выделение уникальных токенов из текста с отбрасыванием стоп-слов + /// Allocation of unique tokens from text with drop of stop words /// - /// Текст - /// Список уникальных токенов без стоп слов + /// Text + /// List of unique tokens without stop words public static IEnumerable ExtractUniqueWordTokensWithoutStopWords(string text) { return ExtractWordTokens(text).DistinctBy(t => t.Word).Where(t => StopWords.IsStopWord(t.Word) == false); diff --git a/ZeroLevel/Services/Semantic/WordLexer.cs b/ZeroLevel/Services/Semantic/WordLexer.cs index 4a8f7ef..394e6f3 100644 --- a/ZeroLevel/Services/Semantic/WordLexer.cs +++ b/ZeroLevel/Services/Semantic/WordLexer.cs @@ -1,6 +1,4 @@ -using ZeroLevel.Services.Semantic; - -namespace ZeroLevel.Services.Semantic +namespace ZeroLevel.Services.Semantic { public class WordLexer : ILexer { diff --git a/ZeroLevel/Services/Serialization/MemoryStreamReader.cs b/ZeroLevel/Services/Serialization/MemoryStreamReader.cs index 6efa0c3..1599603 100644 --- a/ZeroLevel/Services/Serialization/MemoryStreamReader.cs +++ b/ZeroLevel/Services/Serialization/MemoryStreamReader.cs @@ -7,16 +7,13 @@ using System.Text; namespace ZeroLevel.Services.Serialization { /// - /// Обертка над MemoryStream для чтения, с проверкой выхода за пределы потока + /// A wrapper over a MemoryStream for reading, with a check for overflow /// public sealed class MemoryStreamReader : IBinaryReader { private readonly MemoryStream _stream; - /// - /// Конструктор - /// - /// Данные для чтения + public MemoryStreamReader(byte[] data) { if (data == null) @@ -25,7 +22,7 @@ namespace ZeroLevel.Services.Serialization } /// - /// Чтение флага + /// Flag reading /// public bool ReadBoolean() { @@ -34,7 +31,7 @@ namespace ZeroLevel.Services.Serialization return BitConverter.ToBoolean(new byte[1] { ReadByte() }, 0); } /// - /// Чтение байта + /// Reading byte /// public byte ReadByte() { @@ -43,7 +40,7 @@ namespace ZeroLevel.Services.Serialization return (byte)_stream.ReadByte(); } /// - /// Чтение байт-массива + /// Reading bytes /// /// public byte[] ReadBytes() @@ -53,7 +50,7 @@ namespace ZeroLevel.Services.Serialization return ReadBuffer(length); } /// - /// Чтение целого 32-хбитного числа (4 байта) + /// Read 32-bit integer (4 bytes) /// public Int32 ReadInt32() { @@ -67,7 +64,7 @@ namespace ZeroLevel.Services.Serialization return BitConverter.ToInt32(buffer, 0); } /// - /// Чтение целого 64-хбитного числа (8 байт) + /// Read integer 64-bit number (8 bytes) /// public Int64 ReadLong() { @@ -87,7 +84,7 @@ namespace ZeroLevel.Services.Serialization } /// - /// Чтение строки (4 байта на длину + Length байт) + /// Read string (4 bytes per length + Length bytes) /// public string ReadString() { @@ -97,7 +94,7 @@ namespace ZeroLevel.Services.Serialization return Encoding.UTF8.GetString(buffer); } /// - /// Чтение GUID (16 байт) + /// Read GUID (16 bytes) /// public Guid ReadGuid() { @@ -105,7 +102,7 @@ namespace ZeroLevel.Services.Serialization return new Guid(buffer); } /// - /// Чтение байт-пакета (читается размер из указанного количества байт и затем сам пакет прочитанного размера) + /// Reading byte-package (read the size of the specified number of bytes, and then the packet itself read size) /// public byte[] ReadBuffer(int count) { @@ -115,11 +112,11 @@ namespace ZeroLevel.Services.Serialization var buffer = new byte[count]; var readedCount = _stream.Read(buffer, 0, count); if (count != readedCount) - throw new InvalidOperationException(string.Format("The stream returned less data ({0} bytes) than expected ({1} bytes)", count, readedCount)); + throw new InvalidOperationException($"The stream returned less data ({count} bytes) than expected ({readedCount} bytes)"); return buffer; } /// - /// Чтение даты времени + /// Reading the datetime /// /// public DateTime? ReadDateTime() @@ -145,7 +142,7 @@ namespace ZeroLevel.Services.Serialization } /// - /// Проверка не выходит ли чтение данных за пределы потока + /// Check if data reading is outside the stream /// bool CheckOutOfRange(Stream stream, int offset) { @@ -333,9 +330,6 @@ namespace ZeroLevel.Services.Serialization } #endregion - /// - /// Очистка - /// public void Dispose() { _stream.Dispose(); diff --git a/ZeroLevel/Services/Serialization/MemoryStreamWriter.cs b/ZeroLevel/Services/Serialization/MemoryStreamWriter.cs index d0530ff..4daadb0 100644 --- a/ZeroLevel/Services/Serialization/MemoryStreamWriter.cs +++ b/ZeroLevel/Services/Serialization/MemoryStreamWriter.cs @@ -9,7 +9,7 @@ using ZeroLevel.Services.Extensions; namespace ZeroLevel.Services.Serialization { /// - /// Обертка над MemoryStream для записи + /// Wrapper over memorystream for writing /// public sealed class MemoryStreamWriter : IBinaryWriter @@ -29,21 +29,21 @@ namespace ZeroLevel.Services.Serialization _stream = new MemoryStream(); } /// - /// Запись булевого значения (1 байт) + /// Record a boolean value (1 byte) /// public void WriteBoolean(bool val) { _stream.WriteByte(BitConverter.GetBytes(val)[0]); } /// - /// Запись байта (1 байт) + /// Write byte (1 byte) /// public void WriteByte(byte val) { _stream.WriteByte(val); } /// - /// Запись байт массива + /// Write array bytes /// /// public void WriteBytes(byte[] val) @@ -60,14 +60,14 @@ namespace ZeroLevel.Services.Serialization } /// - /// Запись целого 32-хбитного числа (4 байта) + /// Record a 32-bit integer (4 bytes) /// public void WriteInt32(Int32 number) { _stream.Write(BitConverter.GetBytes(number), 0, 4); } /// - /// Запись целого 64-хбитного числа (8 байт) + /// Record an integer 64-bit number (8 bytes) /// public void WriteLong(Int64 number) { @@ -90,7 +90,7 @@ namespace ZeroLevel.Services.Serialization } /// - /// Запись строки (4 байта на длину + Length байт) + /// Write string (4 bytes long + Length bytes) /// public void WriteString(string line) { @@ -106,14 +106,14 @@ namespace ZeroLevel.Services.Serialization } } /// - /// Запись GUID (16 байт) + /// GUID record (16 bytes) /// public void WriteGuid(Guid guid) { _stream.Write(guid.ToByteArray(), 0, 16); } /// - /// Запись даты времени + /// Record the datetime /// /// public void WriteDateTime(DateTime? datetime) diff --git a/ZeroLevel/Services/Shedulling/AsyncShedullerImpl.cs b/ZeroLevel/Services/Shedulling/AsyncShedullerImpl.cs index 95f7be4..f6095be 100644 --- a/ZeroLevel/Services/Shedulling/AsyncShedullerImpl.cs +++ b/ZeroLevel/Services/Shedulling/AsyncShedullerImpl.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Concurrent; using System.Threading.Tasks; -using ZeroLevel.Services.Logging; namespace ZeroLevel.Services.Shedulling { @@ -31,7 +30,7 @@ namespace ZeroLevel.Services.Shedulling private readonly ConcurrentDictionary _repitableAsyncActions = new ConcurrentDictionary(); /// - /// Исполняет действие раз в период, при этом период перерасчитывается по переданной функции при каждом пересоздании задачи + /// Performs an action once a period, while the period is recalculated according to the transferred function at each re-creation of the task. /// /// Функция для расчета следующего периода /// Действие diff --git a/ZeroLevel/Services/Shedulling/ShedullerImpl.cs b/ZeroLevel/Services/Shedulling/ShedullerImpl.cs index 74bc50f..373b87f 100644 --- a/ZeroLevel/Services/Shedulling/ShedullerImpl.cs +++ b/ZeroLevel/Services/Shedulling/ShedullerImpl.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Concurrent; -using ZeroLevel.Services.Logging; namespace ZeroLevel.Services.Shedulling { /// - /// Простой планировщик для периодических и разовых задач выполняемых по расписанию + /// Simple scheduler for periodic and one-time scheduled tasks /// internal class ShedullerImpl : ISheduller @@ -32,11 +31,10 @@ namespace ZeroLevel.Services.Shedulling #region Repitable behaviour private readonly ConcurrentDictionary _repitableActions = new ConcurrentDictionary(); /// - /// Исполняет действие раз в период, при этом период перерасчитывается по переданной функции при каждом пересоздании задачи + /// Performs an action once a period, while the period is recalculated according to the transferred function at each re-creation of the task. /// - /// Функция для расчета следующего периода - /// Действие - /// Идентификатор задания + /// Function to calculate the next period + /// Task ID public long RemindEveryNonlinearPeriod(Func nextEventPeriodCalcFunction, Action callback, bool breakWherError = false) @@ -44,12 +42,11 @@ namespace ZeroLevel.Services.Shedulling return RemindEveryNonlinearPeriod(nextEventPeriodCalcFunction, nextEventPeriodCalcFunction, callback, breakWherError); } /// - /// Исполняет действие раз в период, при этом период перерасчитывается по переданной функции при каждом пересоздании задачи + /// Performs an action once a period, while the period is recalculated according to the transferred function at each re-creation of the task. /// - /// Функция для расчета периода до первого исполнения - /// Функция для расчета периода до последующих исполнений - /// Действие - /// Идентификатор задания + /// The function to calculate the period to the first execution + /// The function for calculating the period until subsequent performances + /// Task ID public long RemindEveryNonlinearPeriod(Func firstEventPeriodCalcFunction, Func nextEventPeriodCalcFunction, Action callback, @@ -82,7 +79,7 @@ namespace ZeroLevel.Services.Shedulling /// /// Функция для расчета следующей даты /// Действие - /// Идентификатор задания + /// Task ID public long RemindEveryNonlinearDate(Func nextEventDateCalcFunction, Action callback, bool breakWherError = false) @@ -130,7 +127,7 @@ namespace ZeroLevel.Services.Shedulling /// Функция для расчет даты первого запуска /// Функция для расчета следующей даты /// Действие - /// Идентификатор задания + /// Task ID public long RemindEveryNonlinearDate(Func firstEventDateCalcFunction, Func nextEventDateCalcFunction, Action callback, @@ -171,7 +168,7 @@ namespace ZeroLevel.Services.Shedulling /// /// Период /// Действие - /// Идентификатор задания + /// Task ID public long RemindEvery(TimeSpan timespan, Action callback, bool breakWherError = false) @@ -184,7 +181,7 @@ namespace ZeroLevel.Services.Shedulling /// Период до первого выполнения /// Период /// Действие - /// Идентификатор задания + /// Task ID public long RemindEvery(TimeSpan first, TimeSpan next, Action callback, diff --git a/ZeroLevel/Services/Specification/Building/SpecificationConstructorParametersResolver.cs b/ZeroLevel/Services/Specification/Building/SpecificationConstructorParametersResolver.cs index 3c33ce6..c5d9aca 100644 --- a/ZeroLevel/Services/Specification/Building/SpecificationConstructorParametersResolver.cs +++ b/ZeroLevel/Services/Specification/Building/SpecificationConstructorParametersResolver.cs @@ -24,12 +24,12 @@ namespace ZeroLevel.Contracts.Specification.Building } } /// - /// Для выбора одного значения из списка + /// To select a single value from the list /// private static readonly Dictionary> _enums = new Dictionary>(); /// - /// Для выбора нескольких значений из списка + /// To select multiple values from the list /// private static readonly Dictionary> _trees = new Dictionary>(); @@ -37,7 +37,7 @@ namespace ZeroLevel.Contracts.Specification.Building private static readonly object _locker = new object(); /// - /// Регистрация перечисления + /// Registration of enumerable /// public static void Register(string paramName, Dictionary map) { @@ -57,7 +57,7 @@ namespace ZeroLevel.Contracts.Specification.Building } } /// - /// Регистрация дерева + /// Tree Registration /// public static void RegisterTree(string paramName, ITree tree) { diff --git a/ZeroLevel/Services/Specification/Building/SpecificationParameter.cs b/ZeroLevel/Services/Specification/Building/SpecificationParameter.cs index 4ddbf19..7c7aa1d 100644 --- a/ZeroLevel/Services/Specification/Building/SpecificationParameter.cs +++ b/ZeroLevel/Services/Specification/Building/SpecificationParameter.cs @@ -3,24 +3,24 @@ namespace ZeroLevel.Contracts.Specification.Building { /// - /// Параметр конструктора спецификации + /// Specification constructor parameter /// public class SpecificationParameter { /// - /// Отображаемое имя + /// Display Name /// public string DisplayName; /// - /// Имя параметра + /// Parameter name /// public string ParameterName; /// - /// Тип параметра + /// Parameter type /// public Type ParameterType; /// - /// Значение параметра + /// Parameter value /// public object Value; } diff --git a/ZeroLevel/Services/Specification/Services/AssemblySpecificationFactory.cs b/ZeroLevel/Services/Specification/Services/AssemblySpecificationFactory.cs index 3949f4d..7c12d6d 100644 --- a/ZeroLevel/Services/Specification/Services/AssemblySpecificationFactory.cs +++ b/ZeroLevel/Services/Specification/Services/AssemblySpecificationFactory.cs @@ -37,7 +37,7 @@ namespace ZeroLevel.Specification { if (false == _filterTypes.ContainsKey(filterName)) { - throw new KeyNotFoundException(string.Format("Not found specification '{0}'", filterName)); + throw new KeyNotFoundException($"Not found specification '{filterName}'"); } return (ISpecification)Activator.CreateInstance(_filterTypes[filterName], args); @@ -47,7 +47,7 @@ namespace ZeroLevel.Specification { if (false == _filterTypes.ContainsKey(filterName)) { - throw new KeyNotFoundException(string.Format("Not found specification '{0}'", filterName)); + throw new KeyNotFoundException($"Not found specification '{filterName}'"); } return _filterTypes[filterName]; } diff --git a/ZeroLevel/Services/Specification/Services/SpecificationBuilder.cs b/ZeroLevel/Services/Specification/Services/SpecificationBuilder.cs index a15b402..f0cb598 100644 --- a/ZeroLevel/Services/Specification/Services/SpecificationBuilder.cs +++ b/ZeroLevel/Services/Specification/Services/SpecificationBuilder.cs @@ -7,23 +7,23 @@ using ZeroLevel.Services.Trees; namespace ZeroLevel.Specification { /// - /// Создает спецификацию используя конкретный конструктор + /// Creates a specification using a specific constructor. /// public class SpecificationBuilder : ISpecificationBuilder, IEquatable { /// - /// Тип спецификации + /// Type of specification /// private readonly Type _instanceType; /// - /// Список параметров конструктора + /// List of Constructor Parameters /// private readonly List _values = new List(); /// - /// Обозначение конструктора + /// Constructor name /// public string Name { get; } public Type FilterType { get { return _instanceType; } } @@ -38,7 +38,7 @@ namespace ZeroLevel.Specification _values = parameters; } /// - /// Обход параметров + /// Parameter traversal /// public void ParametersTraversal(Action parameterHandler) { @@ -48,7 +48,7 @@ namespace ZeroLevel.Specification } } /// - /// Построение спецификации + /// Build specification /// public ISpecification Build() { diff --git a/ZeroLevel/Services/Specification/Services/SpecificationConstructor.cs b/ZeroLevel/Services/Specification/Services/SpecificationConstructor.cs index c687fdb..f288e50 100644 --- a/ZeroLevel/Services/Specification/Services/SpecificationConstructor.cs +++ b/ZeroLevel/Services/Specification/Services/SpecificationConstructor.cs @@ -39,7 +39,7 @@ namespace ZeroLevel.Specification public ISpecificationBuilder GetVariant(string variantName) { if (false == _specificationActivateVariants.ContainsKey(variantName)) - throw new InvalidOperationException(string.Format("Not found variant name {0}", variantName)); + throw new InvalidOperationException($"Not found variant name {variantName}"); return new SpecificationBuilder(variantName, _specificationActivateVariants[variantName], _specificationType); } @@ -48,7 +48,7 @@ namespace ZeroLevel.Specification int index = 0; foreach (var ctor in _specificationType.GetConstructors()) { - var vName = string.Format("{0} #{1:D2}", _specificationType.Name, index); + var vName = $"{_specificationType.Name} #{index:D2}"; var ca = ctor.GetCustomAttribute(); if (null != ca) { diff --git a/ZeroLevel/Services/Text/PlainTextTables/TextTableData.cs b/ZeroLevel/Services/Text/PlainTextTables/TextTableData.cs index 8fe7d7f..1b506f4 100644 --- a/ZeroLevel/Services/Text/PlainTextTables/TextTableData.cs +++ b/ZeroLevel/Services/Text/PlainTextTables/TextTableData.cs @@ -79,7 +79,7 @@ namespace ZeroLevel.Services.PlainTextTables #region API /// - /// Установка заголовков столбцов + /// Setting column headers /// public void SetColumnsHeaders(string[] headers) { @@ -99,7 +99,7 @@ namespace ZeroLevel.Services.PlainTextTables } /// - /// Добавление строки значений + /// Adding a value row /// public void AppendRow(string[] cells) { diff --git a/ZeroLevel/Services/Text/PlainTextTables/TextTableRender.cs b/ZeroLevel/Services/Text/PlainTextTables/TextTableRender.cs index 0c0b3ed..6dc279c 100644 --- a/ZeroLevel/Services/Text/PlainTextTables/TextTableRender.cs +++ b/ZeroLevel/Services/Text/PlainTextTables/TextTableRender.cs @@ -21,7 +21,7 @@ namespace ZeroLevel.Services.PlainTextTables { columns_width[i] += ow; } - // Обновление ширины столбцов при необходимости + // Update column widths as needed if (options.MaxCellWidth > 0) { for (int i = 0; i < columns_width.Length; i++) @@ -47,7 +47,7 @@ namespace ZeroLevel.Services.PlainTextTables var table_width = GetTableWidth(options, columns_width); var table = new StringBuilder(); - // Отрисовка таблицы + // Table drawing var rows = data.Rows.ToArray(); for (int i = 0; i < rows.Length; i++) { @@ -70,20 +70,20 @@ namespace ZeroLevel.Services.PlainTextTables } catch (Exception ex) { - Log.SystemError(ex, "Сбой при преобразовании таблицы"); + Log.SystemError(ex, "Failed to convert table"); return string.Empty; } } /// - /// Рендеринг отображения строки + /// Render row view /// private static List RenderRow(TextTableData.TextTableRow row, TextTableRenderOptions options, int[] columns_width) { var result = new List(); - // Добавление пустых строк если есть padding сверху + // Adding blank lines if there is padding on top if (options.PaddingTop > 0) { for (int i = 0; i < options.PaddingTop; i++) @@ -96,13 +96,13 @@ namespace ZeroLevel.Services.PlainTextTables result.Add(empty); } } - // Разделение значений ячеек на части в зависимости от ширины столбца + // Separation of cell values into parts depending on the width of the column var cells = new List(); for (int i = 0; i < columns_width.Length; i++) { cells.Add(Split(row.Cells[i].Text, columns_width[i], options.PaddingLeft, options.PaddingRight).ToArray()); } - // Определение максимального количества строк по ячейкам (высота строки таблицы) + // Determining the maximum number of rows per cell (row height of the table) var max = cells.Max(c => c.Length); for (int i = 0; i < max; i++) { @@ -118,7 +118,7 @@ namespace ZeroLevel.Services.PlainTextTables } result.Add(line); } - // Добавление пустых строк если есть padding снизу + // Adding blank lines if there is padding below if (options.PaddingBottom > 0) { for (int i = 0; i < options.PaddingBottom; i++) @@ -134,7 +134,7 @@ namespace ZeroLevel.Services.PlainTextTables return result; } /// - /// Разделение текстовой строки на подстроки указанной длины + /// Splitting a text string into substrings of the specified length /// private static IEnumerable Split(string str, int chunkSize, int leftPad, int rightPad) { @@ -169,26 +169,26 @@ namespace ZeroLevel.Services.PlainTextTables return result; } /// - /// Подсчет реальной ширины таблицы, для указанного стиля + /// Calculate the actual width of the table for the specified style /// private static int GetTableWidth(TextTableRenderOptions options, int[] columns_width) { int width = - columns_width.Sum() + // ширина областей текста - columns_width.Length - 1; // границы между ячейками + columns_width.Sum() + // width of text areas + columns_width.Length - 1; // cell boundaries switch (options.Style) { case TextTableStyle.Columns: case TextTableStyle.Simple: case TextTableStyle.Borders: case TextTableStyle.DoubleBorders: - width += 2; // внешние границы + width += 2; // outer borders break; } return width; } /// - /// Отрисовка разделителя столбцов + /// Rendering column separator /// private static void DrawColumnSeparator(StringBuilder sb, TextTableRenderOptions options, int column_index) { @@ -219,10 +219,10 @@ namespace ZeroLevel.Services.PlainTextTables } } /// - /// Отрисовка разделителя строк + /// Row separator rendering /// /// - /// Индекс строки, имеется в виду индекс следующей строки, т.е. 0 - до отрисовки первой строки + /// Line index, meaning the index of the next line, those 0 - before the first line is drawn private static void DrawRowSeparator(StringBuilder sb, TextTableRenderOptions options, int width, int row_index, bool isFirst, bool isLast, int[] columns_width) { diff --git a/ZeroLevel/Services/Text/PlainTextTables/TextTableStyle.cs b/ZeroLevel/Services/Text/PlainTextTables/TextTableStyle.cs index b65f21c..378565b 100644 --- a/ZeroLevel/Services/Text/PlainTextTables/TextTableStyle.cs +++ b/ZeroLevel/Services/Text/PlainTextTables/TextTableStyle.cs @@ -3,31 +3,31 @@ public enum TextTableStyle { /// - /// Без рамок + /// No borders /// NoBorders, /// - /// Рамки из символов !+- + /// Borders of characters! + - /// Simple, /// - /// Рамки из символов +|, только для первой и последней строки и колонок + /// Borders of characters +|, only for the first and last row and columns /// Columns, /// - /// Полные рамки + /// Full borders /// Borders, /// - /// Линия для отделения названий колонок + /// Line to separate column names /// HeaderLine, /// - /// Линии для отделения названий колонок и первого стоблца (названий строк) + /// Lines for separating column names and first column (row names) /// HeaderAndFirstColumn, /// - /// Полные двойные рамки + /// Full double borders /// DoubleBorders, DoubleHeaderLine, diff --git a/ZeroLevel/Services/Trees/TreesVisitor.cs b/ZeroLevel/Services/Trees/TreesVisitor.cs index 1bae29b..f10d8e5 100644 --- a/ZeroLevel/Services/Trees/TreesVisitor.cs +++ b/ZeroLevel/Services/Trees/TreesVisitor.cs @@ -27,14 +27,14 @@ namespace ZeroLevel.Services.Trees return result; } /// - /// Выделяет все ветви дерева, возвращая массив ветвей состоящий из специфицированных значений узлов + /// Selects all branches of the tree, returning an array of branches consisting of the specified node values. /// - /// Тип узлов дерева - /// Тип значений для возвращаемых элементов ветвей - /// Корень - /// Выделяет дочерние узлы для текущего узла - /// Выделяет значение узла - /// Список ветвей дерева + /// Type of tree nodes + /// Value type for returned branch elements + /// Root + /// Selects child nodes for the current node. + /// Select the value of the node + /// List of tree branches public static List SpecifyExtractBranches(T root, Func> childrenExtractor, Func codeExtractor) @@ -53,12 +53,8 @@ namespace ZeroLevel.Services.Trees return result; } /// - /// Выполняет обход ветвей дерева + /// Performs tree branch traversal. /// - /// Тип узлов дерева - /// Корень - /// Выделяет дочерние узлы для текущего узла - /// Обработчик ветви public static void TraversTreeBrunches(T root, Func> childrenExtractor, Action> handler) diff --git a/ZeroLevel/ZeroLevel.csproj b/ZeroLevel/ZeroLevel.csproj index d392b22..f3ab9bd 100644 --- a/ZeroLevel/ZeroLevel.csproj +++ b/ZeroLevel/ZeroLevel.csproj @@ -237,7 +237,6 @@ - diff --git a/ZeroLevel/obj/Debug/ZeroLevel.csproj.CoreCompileInputs.cache b/ZeroLevel/obj/Debug/ZeroLevel.csproj.CoreCompileInputs.cache index 463c314..4f4c026 100644 --- a/ZeroLevel/obj/Debug/ZeroLevel.csproj.CoreCompileInputs.cache +++ b/ZeroLevel/obj/Debug/ZeroLevel.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -3af5ac7a6b742028005a8a0757e8f6fbb4fd20fa +1f24b3553bbdd4eeac0eb648e295a8fad68b0131