Refactoring and localization

pull/1/head
Ogoun 6 years ago
parent 618d1de5ff
commit d30d681f0c

@ -6,19 +6,32 @@ namespace ZeroExample
public sealed class MyFirstApp public sealed class MyFirstApp
: BaseWindowsService, IZeroService : BaseWindowsService, IZeroService
{ {
public MyFirstApp() : base("MyApp") { Log.AddConsoleLogger(); } public MyFirstApp() : base("MyApp")
public override void PauseAction() { } {
public override void ResumeAction() { } Log.AddConsoleLogger();
}
public override void PauseAction()
{
}
public override void ResumeAction()
{
}
public override void StartAction() public override void StartAction()
{ {
Log.Info("Started"); Log.Info("Started");
} }
public override void StopAction() { }
public override void StopAction()
{
}
} }
class Program internal class Program
{ {
static void Main(string[] args) private static void Main(string[] args)
{ {
Bootstrap.Startup<MyFirstApp>(args); Bootstrap.Startup<MyFirstApp>(args);
} }

@ -1,5 +1,4 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup> </startup>
<appSettings> <appSettings>
<add key="console" value="true"/> <add key="console" value="true" />
<add key="port" value="8885"/> <add key="port" value="8885" />
</appSettings> </appSettings>
<runtime> <runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

@ -11,6 +11,7 @@ namespace ZeroLevel.Discovery
public abstract class BaseController : ApiController public abstract class BaseController : ApiController
{ {
#region Responce create helpers #region Responce create helpers
public static HttpResponseMessage BadRequestAnswer(HttpRequestMessage request, string message) public static HttpResponseMessage BadRequestAnswer(HttpRequestMessage request, string message)
{ {
return request.CreateSelfDestroyingResponse(HttpStatusCode.BadRequest, return request.CreateSelfDestroyingResponse(HttpStatusCode.BadRequest,
@ -90,6 +91,7 @@ namespace ZeroLevel.Discovery
} }
return null; return null;
} }
#endregion
#endregion Responce create helpers
} }
} }

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http; using System.Web.Http;
using System.Web.Http.Description; using System.Web.Http.Description;
using ZeroLevel.Models; using ZeroLevel.Models;

@ -1,8 +1,8 @@
namespace ZeroLevel.Discovery namespace ZeroLevel.Discovery
{ {
class Program internal class Program
{ {
static void Main(string[] args) private static void Main(string[] args)
{ {
Bootstrap.Startup<DiscoveryService>(args); Bootstrap.Startup<DiscoveryService>(args);
} }

@ -1,5 +1,4 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following

@ -3,7 +3,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Threading; using System.Threading;
using ZeroLevel.Microservices; using ZeroLevel.Microservices;
using ZeroLevel.Models; using ZeroLevel.Models;
@ -24,6 +23,7 @@ namespace ZeroLevel.Discovery
} }
#region Snapshot #region Snapshot
private static readonly object _snapshot_lock = new object(); private static readonly object _snapshot_lock = new object();
private void Save() private void Save()
@ -89,7 +89,8 @@ namespace ZeroLevel.Discovery
Log.Error(ex, "Fault load snapshot"); Log.Error(ex, "Fault load snapshot");
} }
} }
#endregion
#endregion Snapshot
private bool Ping(string protocol, string endpoint, string msg) private bool Ping(string protocol, string endpoint, string msg)
{ {

@ -67,6 +67,7 @@ namespace ZeroLevel.Discovery
} }
private static bool _log_request_response; private static bool _log_request_response;
public static void StartWebPanel(int port, public static void StartWebPanel(int port,
bool log_request_response) bool log_request_response)
{ {

@ -6,8 +6,11 @@ namespace ZeroLevel.Microservices.Contracts
public interface IDiscoveryClient public interface IDiscoveryClient
{ {
void Register(MicroserviceInfo info); void Register(MicroserviceInfo info);
IEnumerable<ServiceEndpointInfo> GetServiceEndpoints(string serviceKey); IEnumerable<ServiceEndpointInfo> GetServiceEndpoints(string serviceKey);
IEnumerable<ServiceEndpointInfo> GetServiceEndpointsByGroup(string serviceGroup); IEnumerable<ServiceEndpointInfo> GetServiceEndpointsByGroup(string serviceGroup);
IEnumerable<ServiceEndpointInfo> GetServiceEndpointsByType(string serviceType); IEnumerable<ServiceEndpointInfo> GetServiceEndpointsByType(string serviceType);
ServiceEndpointInfo GetService(string serviceKey, string endpoint); ServiceEndpointInfo GetService(string serviceKey, string endpoint);

@ -18,9 +18,11 @@ namespace ZeroLevel.Microservices
public MicroserviceInfo ServiceInfo { get; set; } public MicroserviceInfo ServiceInfo { get; set; }
public ExService Server { get; set; } public ExService Server { get; set; }
} }
private bool _disposed = false; private bool _disposed = false;
private readonly long _registerTaskKey = -1; private readonly long _registerTaskKey = -1;
private readonly IDiscoveryClient _discoveryClient; private readonly IDiscoveryClient _discoveryClient;
private readonly ConcurrentDictionary<string, MetaService> _services private readonly ConcurrentDictionary<string, MetaService> _services
= new ConcurrentDictionary<string, MetaService>(); = new ConcurrentDictionary<string, MetaService>();
@ -116,6 +118,7 @@ namespace ZeroLevel.Microservices
} }
#region Private methods #region Private methods
private void ValidateService(IExchangeService service) private void ValidateService(IExchangeService service)
{ {
if (string.IsNullOrWhiteSpace(service.Protocol)) if (string.IsNullOrWhiteSpace(service.Protocol))
@ -127,6 +130,7 @@ namespace ZeroLevel.Microservices
throw new ArgumentNullException("Service.Key"); throw new ArgumentNullException("Service.Key");
} }
} }
private void ValidateService(MicroserviceInfo service) private void ValidateService(MicroserviceInfo service)
{ {
if (string.IsNullOrWhiteSpace(service.Protocol)) if (string.IsNullOrWhiteSpace(service.Protocol))
@ -218,9 +222,11 @@ namespace ZeroLevel.Microservices
_discoveryClient.Register(service); _discoveryClient.Register(service);
} }
} }
#endregion
#endregion Private methods
#region Utils #region Utils
private static Delegate CreateDelegate(MethodInfo methodInfo, object target) private static Delegate CreateDelegate(MethodInfo methodInfo, object target)
{ {
Func<Type[], Type> getType; Func<Type[], Type> getType;
@ -241,9 +247,11 @@ namespace ZeroLevel.Microservices
} }
return Delegate.CreateDelegate(getType(types.ToArray()), target, methodInfo.Name); return Delegate.CreateDelegate(getType(types.ToArray()), target, methodInfo.Name);
} }
#endregion
#endregion Utils
#region Inboxes #region Inboxes
/// <summary> /// <summary>
/// Регистрация обработчика входящих сообщений /// Регистрация обработчика входящих сообщений
/// </summary> /// </summary>
@ -263,6 +271,7 @@ namespace ZeroLevel.Microservices
Log.SystemError(ex, $"[Exchange] Register inbox handler error. Protocol '{meta.ServiceInfo.Protocol}'. Inbox '{inbox}'. Service '{meta.ServiceInfo.ServiceKey}'"); Log.SystemError(ex, $"[Exchange] Register inbox handler error. Protocol '{meta.ServiceInfo.Protocol}'. Inbox '{inbox}'. Service '{meta.ServiceInfo.ServiceKey}'");
} }
} }
/// <summary> /// <summary>
/// Регистрация метода отдающего ответ на входящий запрос /// Регистрация метода отдающего ответ на входящий запрос
/// </summary> /// </summary>
@ -283,6 +292,7 @@ namespace ZeroLevel.Microservices
Log.SystemError(ex, $"[Exchange] Register inbox replier error. Protocol '{meta.ServiceInfo.Protocol}'. Inbox '{inbox}'. Service '{meta.ServiceInfo.ServiceKey}'"); Log.SystemError(ex, $"[Exchange] Register inbox replier error. Protocol '{meta.ServiceInfo.Protocol}'. Inbox '{inbox}'. Service '{meta.ServiceInfo.ServiceKey}'");
} }
} }
/// <summary> /// <summary>
/// Регистрация метода отдающего ответ на входящий запрос, не принимающего входящих данных /// Регистрация метода отдающего ответ на входящий запрос, не принимающего входящих данных
/// </summary> /// </summary>
@ -302,9 +312,11 @@ namespace ZeroLevel.Microservices
Log.SystemError(ex, $"[Exchange] Register inbox replier error. Protocol '{meta.ServiceInfo.Protocol}'. Inbox '{inbox}'. Service '{meta.ServiceInfo.ServiceKey}'"); Log.SystemError(ex, $"[Exchange] Register inbox replier error. Protocol '{meta.ServiceInfo.Protocol}'. Inbox '{inbox}'. Service '{meta.ServiceInfo.ServiceKey}'");
} }
} }
#endregion
#endregion Inboxes
#region Transport helpers #region Transport helpers
/// <summary> /// <summary>
/// Call service with round-robin balancing /// Call service with round-robin balancing
/// </summary> /// </summary>
@ -503,7 +515,8 @@ namespace ZeroLevel.Microservices
} }
} }
} }
#endregion
#endregion Transport helpers
public void Dispose() public void Dispose()
{ {

@ -4,10 +4,8 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using ZeroLevel.Microservices.Contracts; using ZeroLevel.Microservices.Contracts;
using ZeroLevel.Microservices.Model;
using ZeroLevel.Network.Microservices; using ZeroLevel.Network.Microservices;
using ZeroLevel.Services.Network; using ZeroLevel.Services.Network;
using ZeroLevel.Services.Serialization;
namespace ZeroLevel.Microservices namespace ZeroLevel.Microservices
{ {
@ -21,12 +19,14 @@ namespace ZeroLevel.Microservices
private readonly ExServiceHost _host; private readonly ExServiceHost _host;
#region Ctor #region Ctor
public Exchange(IDiscoveryClient discoveryClient) public Exchange(IDiscoveryClient discoveryClient)
{ {
this._discoveryClient = discoveryClient ?? throw new ArgumentNullException(nameof(discoveryClient)); this._discoveryClient = discoveryClient ?? throw new ArgumentNullException(nameof(discoveryClient));
this._host = new ExServiceHost(this._discoveryClient); this._host = new ExServiceHost(this._discoveryClient);
} }
#endregion
#endregion Ctor
/// <summary> /// <summary>
/// Регистрация сервиса /// Регистрация сервиса
@ -42,6 +42,7 @@ namespace ZeroLevel.Microservices
} }
#region Balanced send #region Balanced send
/// <summary> /// <summary>
/// Отправка сообщения сервису /// Отправка сообщения сервису
/// </summary> /// </summary>
@ -63,9 +64,11 @@ namespace ZeroLevel.Microservices
} }
public bool Send<T>(string serviceKey, T data) => Send(serviceKey, ZBaseNetwork.DEFAULT_MESSAGE_INBOX, data); public bool Send<T>(string serviceKey, T data) => Send(serviceKey, ZBaseNetwork.DEFAULT_MESSAGE_INBOX, data);
#endregion
#endregion Balanced send
#region Balanced request #region Balanced request
public Tresp Request<Treq, Tresp>(string serviceKey, string inbox, Treq data) public Tresp Request<Treq, Tresp>(string serviceKey, string inbox, Treq data)
{ {
Tresp response = default(Tresp); Tresp response = default(Tresp);
@ -157,9 +160,11 @@ namespace ZeroLevel.Microservices
public Tresp Request<Tresp>(string serviceKey) => public Tresp Request<Tresp>(string serviceKey) =>
Request<Tresp>(serviceKey, ZBaseNetwork.DEFAULT_REQUEST_INBOX); Request<Tresp>(serviceKey, ZBaseNetwork.DEFAULT_REQUEST_INBOX);
#endregion
#endregion Balanced request
#region Direct request #region Direct request
public Tresp RequestDirect<Treq, Tresp>(string endpoint, string serviceKey, string inbox, Treq data) public Tresp RequestDirect<Treq, Tresp>(string endpoint, string serviceKey, string inbox, Treq data)
{ {
Tresp response = default(Tresp); Tresp response = default(Tresp);
@ -251,9 +256,11 @@ namespace ZeroLevel.Microservices
public Tresp RequestDirect<Tresp>(string endpoint, string serviceKey) => public Tresp RequestDirect<Tresp>(string endpoint, string serviceKey) =>
RequestDirect<Tresp>(endpoint, serviceKey, ZBaseNetwork.DEFAULT_REQUEST_INBOX); RequestDirect<Tresp>(endpoint, serviceKey, ZBaseNetwork.DEFAULT_REQUEST_INBOX);
#endregion
#endregion Direct request
#region Broadcast #region Broadcast
/// <summary> /// <summary>
/// Отправка сообщения всем сервисам с указанным ключом в указанный обработчик /// Отправка сообщения всем сервисам с указанным ключом в указанный обработчик
/// </summary> /// </summary>
@ -287,6 +294,7 @@ namespace ZeroLevel.Microservices
} }
return false; return false;
} }
/// <summary> /// <summary>
/// Отправка сообщения всем сервисам с указанным ключом, в обработчик по умолчанию /// Отправка сообщения всем сервисам с указанным ключом, в обработчик по умолчанию
/// </summary> /// </summary>
@ -295,6 +303,7 @@ namespace ZeroLevel.Microservices
/// <param name="data">Сообщение</param> /// <param name="data">Сообщение</param>
/// <returns>true - при успешной отправке</returns> /// <returns>true - при успешной отправке</returns>
public bool SendBroadcast<T>(string serviceKey, T data) => SendBroadcast(serviceKey, ZBaseNetwork.DEFAULT_MESSAGE_INBOX, data); public bool SendBroadcast<T>(string serviceKey, T data) => SendBroadcast(serviceKey, ZBaseNetwork.DEFAULT_MESSAGE_INBOX, data);
/// <summary> /// <summary>
/// Отправка сообщения всем сервисам конкретного типа в указанный обработчик /// Отправка сообщения всем сервисам конкретного типа в указанный обработчик
/// </summary> /// </summary>
@ -328,6 +337,7 @@ namespace ZeroLevel.Microservices
} }
return false; return false;
} }
/// <summary> /// <summary>
/// Отправка сообщения всем сервисам конкретного типа, в обработчик по умолчанию /// Отправка сообщения всем сервисам конкретного типа, в обработчик по умолчанию
/// </summary> /// </summary>
@ -337,6 +347,7 @@ namespace ZeroLevel.Microservices
/// <returns>true - при успешной отправке</returns> /// <returns>true - при успешной отправке</returns>
public bool SendBroadcastByType<T>(string serviceType, T data) => public bool SendBroadcastByType<T>(string serviceType, T data) =>
SendBroadcastByType(serviceType, ZBaseNetwork.DEFAULT_MESSAGE_INBOX, data); SendBroadcastByType(serviceType, ZBaseNetwork.DEFAULT_MESSAGE_INBOX, data);
/// <summary> /// <summary>
/// Отправка сообщения всем сервисам конкретной группы в указанный обработчик /// Отправка сообщения всем сервисам конкретной группы в указанный обработчик
/// </summary> /// </summary>
@ -370,6 +381,7 @@ namespace ZeroLevel.Microservices
} }
return false; return false;
} }
/// <summary> /// <summary>
/// Отправка сообщения всем сервисам конкретной группы, в обработчик по умолчанию /// Отправка сообщения всем сервисам конкретной группы, в обработчик по умолчанию
/// </summary> /// </summary>
@ -379,6 +391,7 @@ namespace ZeroLevel.Microservices
/// <returns>true - при успешной отправке</returns> /// <returns>true - при успешной отправке</returns>
public bool SendBroadcastByGroup<T>(string serviceGroup, T data) => public bool SendBroadcastByGroup<T>(string serviceGroup, T data) =>
SendBroadcastByGroup(serviceGroup, ZBaseNetwork.DEFAULT_MESSAGE_INBOX, data); SendBroadcastByGroup(serviceGroup, ZBaseNetwork.DEFAULT_MESSAGE_INBOX, data);
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по ключу /// Широковещательный опрос сервисов по ключу
/// </summary> /// </summary>
@ -402,6 +415,7 @@ namespace ZeroLevel.Microservices
} }
return Enumerable.Empty<Tresp>(); return Enumerable.Empty<Tresp>();
} }
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по ключу, без сообщеня запроса /// Широковещательный опрос сервисов по ключу, без сообщеня запроса
/// </summary> /// </summary>
@ -423,6 +437,7 @@ namespace ZeroLevel.Microservices
} }
return Enumerable.Empty<Tresp>(); return Enumerable.Empty<Tresp>();
} }
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по ключу, в обработчик по умолчанию /// Широковещательный опрос сервисов по ключу, в обработчик по умолчанию
/// </summary> /// </summary>
@ -434,6 +449,7 @@ namespace ZeroLevel.Microservices
/// <returns>true - в случае успешной рассылки</returns> /// <returns>true - в случае успешной рассылки</returns>
public IEnumerable<Tresp> RequestBroadcast<Treq, Tresp>(string serviceKey, Treq data) => public IEnumerable<Tresp> RequestBroadcast<Treq, Tresp>(string serviceKey, Treq data) =>
RequestBroadcast<Treq, Tresp>(serviceKey, ZBaseNetwork.DEFAULT_REQUEST_INBOX, data); RequestBroadcast<Treq, Tresp>(serviceKey, ZBaseNetwork.DEFAULT_REQUEST_INBOX, data);
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по ключу, без сообщеня запроса, в обработчик по умолчанию /// Широковещательный опрос сервисов по ключу, без сообщеня запроса, в обработчик по умолчанию
/// </summary> /// </summary>
@ -443,6 +459,7 @@ namespace ZeroLevel.Microservices
/// <returns>true - в случае успешной рассылки</returns> /// <returns>true - в случае успешной рассылки</returns>
public IEnumerable<Tresp> RequestBroadcast<Tresp>(string serviceKey) => public IEnumerable<Tresp> RequestBroadcast<Tresp>(string serviceKey) =>
RequestBroadcast<Tresp>(serviceKey, ZBaseNetwork.DEFAULT_REQUEST_INBOX); RequestBroadcast<Tresp>(serviceKey, ZBaseNetwork.DEFAULT_REQUEST_INBOX);
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по типу сервису /// Широковещательный опрос сервисов по типу сервису
/// </summary> /// </summary>
@ -466,6 +483,7 @@ namespace ZeroLevel.Microservices
} }
return Enumerable.Empty<Tresp>(); return Enumerable.Empty<Tresp>();
} }
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по типу сервису, без сообщеня запроса /// Широковещательный опрос сервисов по типу сервису, без сообщеня запроса
/// </summary> /// </summary>
@ -487,6 +505,7 @@ namespace ZeroLevel.Microservices
} }
return Enumerable.Empty<Tresp>(); return Enumerable.Empty<Tresp>();
} }
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по типу сервису, в обработчик по умолчанию /// Широковещательный опрос сервисов по типу сервису, в обработчик по умолчанию
/// </summary> /// </summary>
@ -498,6 +517,7 @@ namespace ZeroLevel.Microservices
/// <returns>true - в случае успешной рассылки</returns> /// <returns>true - в случае успешной рассылки</returns>
public IEnumerable<Tresp> RequestBroadcastByType<Treq, Tresp>(string serviceType, Treq data) => public IEnumerable<Tresp> RequestBroadcastByType<Treq, Tresp>(string serviceType, Treq data) =>
RequestBroadcastByType<Treq, Tresp>(serviceType, ZBaseNetwork.DEFAULT_REQUEST_INBOX, data); RequestBroadcastByType<Treq, Tresp>(serviceType, ZBaseNetwork.DEFAULT_REQUEST_INBOX, data);
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по типу, без сообщеня запроса, в обработчик по умолчанию /// Широковещательный опрос сервисов по типу, без сообщеня запроса, в обработчик по умолчанию
/// </summary> /// </summary>
@ -507,6 +527,7 @@ namespace ZeroLevel.Microservices
/// <returns>true - в случае успешной рассылки</returns> /// <returns>true - в случае успешной рассылки</returns>
public IEnumerable<Tresp> RequestBroadcastByType<Tresp>(string serviceType) => public IEnumerable<Tresp> RequestBroadcastByType<Tresp>(string serviceType) =>
RequestBroadcastByType<Tresp>(serviceType, ZBaseNetwork.DEFAULT_REQUEST_INBOX); RequestBroadcastByType<Tresp>(serviceType, ZBaseNetwork.DEFAULT_REQUEST_INBOX);
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по группе сервисов /// Широковещательный опрос сервисов по группе сервисов
/// </summary> /// </summary>
@ -530,6 +551,7 @@ namespace ZeroLevel.Microservices
} }
return Enumerable.Empty<Tresp>(); return Enumerable.Empty<Tresp>();
} }
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по группе сервисов, без сообщения запроса /// Широковещательный опрос сервисов по группе сервисов, без сообщения запроса
/// </summary> /// </summary>
@ -551,6 +573,7 @@ namespace ZeroLevel.Microservices
} }
return Enumerable.Empty<Tresp>(); return Enumerable.Empty<Tresp>();
} }
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по группе сервисов в обработчик по умолчанию /// Широковещательный опрос сервисов по группе сервисов в обработчик по умолчанию
/// </summary> /// </summary>
@ -562,6 +585,7 @@ namespace ZeroLevel.Microservices
/// <returns>true - в случае успешной рассылки</returns> /// <returns>true - в случае успешной рассылки</returns>
public IEnumerable<Tresp> RequestBroadcastByGroup<Treq, Tresp>(string serviceGroup, Treq data) => public IEnumerable<Tresp> RequestBroadcastByGroup<Treq, Tresp>(string serviceGroup, Treq data) =>
RequestBroadcastByGroup<Treq, Tresp>(serviceGroup, ZBaseNetwork.DEFAULT_REQUEST_INBOX, data); RequestBroadcastByGroup<Treq, Tresp>(serviceGroup, ZBaseNetwork.DEFAULT_REQUEST_INBOX, data);
/// <summary> /// <summary>
/// Широковещательный опрос сервисов по группе сервисов, без сообщения запроса, в обработчик по умолчанию /// Широковещательный опрос сервисов по группе сервисов, без сообщения запроса, в обработчик по умолчанию
/// </summary> /// </summary>
@ -573,6 +597,7 @@ namespace ZeroLevel.Microservices
RequestBroadcastByGroup<Tresp>(serviceGroup, ZBaseNetwork.DEFAULT_REQUEST_INBOX); RequestBroadcastByGroup<Tresp>(serviceGroup, ZBaseNetwork.DEFAULT_REQUEST_INBOX);
#region Private #region Private
private IEnumerable<Tresp> _RequestBroadcast<Treq, Tresp>(List<IExClient> clients, string inbox, Treq data) private IEnumerable<Tresp> _RequestBroadcast<Treq, Tresp>(List<IExClient> clients, string inbox, Treq data)
{ {
var response = new List<Tresp>(); var response = new List<Tresp>();
@ -628,9 +653,10 @@ namespace ZeroLevel.Microservices
} }
return response; return response;
} }
#endregion
#endregion #endregion Private
#endregion Broadcast
public void Dispose() public void Dispose()
{ {

@ -19,6 +19,7 @@ namespace ZeroLevel.Microservices.Model
public byte[] Payload { get; set; } public byte[] Payload { get; set; }
#region IBinarySerializable #region IBinarySerializable
public void Deserialize(IBinaryReader reader) public void Deserialize(IBinaryReader reader)
{ {
this.Id = reader.ReadGuid(); this.Id = reader.ReadGuid();
@ -40,19 +41,23 @@ namespace ZeroLevel.Microservices.Model
writer.WriteInt32((int)this.CheckpointType); writer.WriteInt32((int)this.CheckpointType);
writer.WriteBytes(this.Payload); writer.WriteBytes(this.Payload);
} }
#endregion
#endregion IBinarySerializable
#region Ctors #region Ctors
public Checkpoint() public Checkpoint()
{ {
this.Id = Guid.NewGuid(); this.Id = Guid.NewGuid();
this.Timestamp = DateTime.Now.Ticks; this.Timestamp = DateTime.Now.Ticks;
} }
public Checkpoint(Guid id) public Checkpoint(Guid id)
{ {
this.Timestamp = DateTime.Now.Ticks; this.Timestamp = DateTime.Now.Ticks;
this.Id = id; this.Id = id;
} }
public Checkpoint(Checkpoint other) public Checkpoint(Checkpoint other)
{ {
this.Id = other.Id; this.Id = other.Id;
@ -63,9 +68,11 @@ namespace ZeroLevel.Microservices.Model
this.Payload = other.Payload; this.Payload = other.Payload;
this.ReasonPhrase = other.ReasonPhrase; this.ReasonPhrase = other.ReasonPhrase;
} }
#endregion
#endregion Ctors
#region Equals & Hash #region Equals & Hash
public override int GetHashCode() public override int GetHashCode()
{ {
return base.GetHashCode(); return base.GetHashCode();
@ -75,16 +82,20 @@ namespace ZeroLevel.Microservices.Model
{ {
return this.Equals(obj as Checkpoint); return this.Equals(obj as Checkpoint);
} }
#endregion
#endregion Equals & Hash
#region ICloneable #region ICloneable
public object Clone() public object Clone()
{ {
return new Checkpoint(this); return new Checkpoint(this);
} }
#endregion
#endregion ICloneable
#region IEquatable #region IEquatable
public bool Equals(Checkpoint other) public bool Equals(Checkpoint other)
{ {
if (this.Id != other.Id) return false; if (this.Id != other.Id) return false;
@ -96,6 +107,7 @@ namespace ZeroLevel.Microservices.Model
if (false == ArrayExtensions.Equals(this.Payload, other.Payload)) return false; if (false == ArrayExtensions.Equals(this.Payload, other.Payload)) return false;
return true; return true;
} }
#endregion
#endregion IEquatable
} }
} }

@ -1,5 +1,4 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following

@ -15,6 +15,7 @@ namespace ZeroLevel.Microservices
BaseProxy, IDiscoveryClient BaseProxy, IDiscoveryClient
{ {
#region WebAPI #region WebAPI
private IEnumerable<ServiceEndpointsInfo> GetRecords() private IEnumerable<ServiceEndpointsInfo> GetRecords()
{ {
return GET<IEnumerable<ServiceEndpointsInfo>>("api/v0/routes"); return GET<IEnumerable<ServiceEndpointsInfo>>("api/v0/routes");
@ -24,13 +25,16 @@ namespace ZeroLevel.Microservices
{ {
return POST<InvokeResult>("api/v0/routes", info); return POST<InvokeResult>("api/v0/routes", info);
} }
#endregion
#endregion WebAPI
// Таблица по ключам // Таблица по ключам
private readonly ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>> _tableByKey = private readonly ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>> _tableByKey =
new ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>>(); new ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>>();
private readonly ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>> _tableByGroups = private readonly ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>> _tableByGroups =
new ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>>(); new ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>>();
private readonly ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>> _tableByTypes = private readonly ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>> _tableByTypes =
new ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>>(); new ConcurrentDictionary<string, RoundRobinCollection<ServiceEndpointInfo>>();

@ -8,6 +8,7 @@ namespace ZeroLevel.Models
public abstract class BaseModel public abstract class BaseModel
{ {
#region Equal #region Equal
public bool Equals(BaseModel other) public bool Equals(BaseModel other)
{ {
if (this == null) if (this == null)
@ -30,10 +31,13 @@ namespace ZeroLevel.Models
} }
public static bool operator ==(BaseModel first, BaseModel second) => Equals(first, second); public static bool operator ==(BaseModel first, BaseModel second) => Equals(first, second);
public static bool operator !=(BaseModel first, BaseModel second) => !Equals(first, second); public static bool operator !=(BaseModel first, BaseModel second) => !Equals(first, second);
#endregion
#endregion Equal
public abstract override int GetHashCode(); public abstract override int GetHashCode();
public abstract object Clone(); public abstract object Clone();
} }
} }

@ -17,32 +17,39 @@ namespace ZeroLevel.Models
/// Id /// Id
/// </summary> /// </summary>
public Guid Id { get; set; } public Guid Id { get; set; }
/// <summary> /// <summary>
/// File name /// File name
/// </summary> /// </summary>
public string FileName { get; set; } public string FileName { get; set; }
/// <summary> /// <summary>
/// Content type (pdf, doc, etc.) /// Content type (pdf, doc, etc.)
/// </summary> /// </summary>
public string ContentType { get; set; } public string ContentType { get; set; }
/// <summary> /// <summary>
/// Content /// Content
/// </summary> /// </summary>
public byte[] Document { get; set; } public byte[] Document { get; set; }
/// <summary> /// <summary>
/// Creation date /// Creation date
/// </summary> /// </summary>
public DateTime Created { get; set; } public DateTime Created { get; set; }
/// <summary> /// <summary>
/// Optional headers /// Optional headers
/// </summary> /// </summary>
public List<Header> Headers { get; set; } public List<Header> Headers { get; set; }
/// <summary> /// <summary>
/// Categories /// Categories
/// </summary> /// </summary>
public List<Category> Categories { get; set; } public List<Category> Categories { get; set; }
#region Ctors #region Ctors
public BinaryDocument() public BinaryDocument()
{ {
Created = DateTime.Now; Created = DateTime.Now;
@ -58,9 +65,11 @@ namespace ZeroLevel.Models
Deserialize(reader); Deserialize(reader);
} }
} }
#endregion
#endregion Ctors
#region IBinarySerializable #region IBinarySerializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteGuid(this.Id); writer.WriteGuid(this.Id);
@ -82,9 +91,11 @@ namespace ZeroLevel.Models
this.Headers = reader.ReadCollection<Header>(); this.Headers = reader.ReadCollection<Header>();
this.Categories = reader.ReadCollection<Category>(); this.Categories = reader.ReadCollection<Category>();
} }
#endregion
#endregion IBinarySerializable
#region Equals & Hash #region Equals & Hash
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
return this.Equals(obj as BinaryDocument); return this.Equals(obj as BinaryDocument);
@ -111,7 +122,8 @@ namespace ZeroLevel.Models
{ {
return Id.GetHashCode(); return Id.GetHashCode();
} }
#endregion
#endregion Equals & Hash
public object Clone() public object Clone()
{ {

@ -12,10 +12,13 @@ namespace ZeroLevel.Models
IBinarySerializable IBinarySerializable
{ {
#region Static #region Static
private static readonly InvokeResult _successResultWitoutComment = new InvokeResult(true, String.Empty); private static readonly InvokeResult _successResultWitoutComment = new InvokeResult(true, String.Empty);
#endregion
#endregion Static
#region Ctor #region Ctor
public InvokeResult() public InvokeResult()
{ {
} }
@ -25,35 +28,43 @@ namespace ZeroLevel.Models
Success = success; Success = success;
Comment = comment; Comment = comment;
} }
#endregion
#endregion Ctor
#region Properties #region Properties
/// <summary> /// <summary>
/// true when action successfully invoked /// true when action successfully invoked
/// </summary> /// </summary>
[DataMember] [DataMember]
public bool Success; public bool Success;
/// <summary> /// <summary>
/// Comment /// Comment
/// </summary> /// </summary>
[DataMember] [DataMember]
public string Comment; public string Comment;
#endregion
#endregion Properties
#region Fabric methods #region Fabric methods
/// <summary> /// <summary>
/// Error when action invoking /// Error when action invoking
/// </summary> /// </summary>
public static InvokeResult Fault(string comment) { return new InvokeResult(false, comment); } public static InvokeResult Fault(string comment) { return new InvokeResult(false, comment); }
/// <summary> /// <summary>
/// Successfully /// Successfully
/// </summary> /// </summary>
public static InvokeResult Succeeding(string comment = "") { return new InvokeResult(true, comment); } public static InvokeResult Succeeding(string comment = "") { return new InvokeResult(true, comment); }
/// <summary> /// <summary>
/// Successfully /// Successfully
/// </summary> /// </summary>
public static InvokeResult Succeeding() { return _successResultWitoutComment; } public static InvokeResult Succeeding() { return _successResultWitoutComment; }
#endregion
#endregion Fabric methods
public virtual void Serialize(IBinaryWriter writer) public virtual void Serialize(IBinaryWriter writer)
{ {
@ -75,6 +86,7 @@ namespace ZeroLevel.Models
public T Value { get { return _value; } } public T Value { get { return _value; } }
#region Ctor #region Ctor
public InvokeResult(bool success, string comment) public InvokeResult(bool success, string comment)
{ {
Success = success; Success = success;
@ -87,12 +99,22 @@ namespace ZeroLevel.Models
Success = success; Success = success;
Comment = comment; Comment = comment;
} }
#endregion
#endregion Ctor
#region Fabric methods #region Fabric methods
public static InvokeResult<T> Succeeding(T value, string comment = "") { return new InvokeResult<T>(value, true, comment); }
public static InvokeResult<T> Fault<T>(string comment) { return new InvokeResult<T>(false, comment); } public static InvokeResult<T> Succeeding(T value, string comment = "")
#endregion {
return new InvokeResult<T>(value, true, comment);
}
public static InvokeResult<T> Fault<T>(string comment)
{
return new InvokeResult<T>(false, comment);
}
#endregion Fabric methods
public override void Serialize(IBinaryWriter writer) public override void Serialize(IBinaryWriter writer)
{ {

@ -1,5 +1,4 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following

@ -22,7 +22,6 @@ namespace ZeroLevel.Services.Applications
public ZeroServiceState State => _state; public ZeroServiceState State => _state;
private ZeroServiceState _state; private ZeroServiceState _state;
private ManualResetEvent InteraciveModeWorkingFlag = new ManualResetEvent(false); private ManualResetEvent InteraciveModeWorkingFlag = new ManualResetEvent(false);
public void InteractiveStart(string[] args) public void InteractiveStart(string[] args)
@ -35,13 +34,19 @@ namespace ZeroLevel.Services.Applications
} }
#region IZeroService #region IZeroService
public abstract void StartAction(); public abstract void StartAction();
public abstract void StopAction(); public abstract void StopAction();
public abstract void PauseAction(); public abstract void PauseAction();
public abstract void ResumeAction(); public abstract void ResumeAction();
#endregion
#endregion IZeroService
#region Windows service #region Windows service
protected override void OnStart(string[] args) protected override void OnStart(string[] args)
{ {
if (_state == ZeroServiceState.Initialized) if (_state == ZeroServiceState.Initialized)
@ -116,6 +121,7 @@ namespace ZeroLevel.Services.Applications
} }
} }
} }
#endregion
#endregion Windows service
} }
} }

@ -57,6 +57,7 @@ namespace ZeroLevel
Log.Fatal(ex, "[Bootstrap] Fault service install"); Log.Fatal(ex, "[Bootstrap] Fault service install");
} }
} }
/// <summary> /// <summary>
/// Uninstall from windows services /// Uninstall from windows services
/// </summary> /// </summary>

@ -5,8 +5,11 @@
ZeroServiceState State { get; } ZeroServiceState State { get; }
void StartAction(); void StartAction();
void StopAction(); void StopAction();
void PauseAction(); void PauseAction();
void ResumeAction(); void ResumeAction();
void InteractiveStart(string[] args); void InteractiveStart(string[] args);

@ -179,6 +179,7 @@ namespace ZeroLevel.Services.Async
public IAsyncWaitQueue<object> WaitQueue { get { return _cv._queue; } } public IAsyncWaitQueue<object> WaitQueue { get { return _cv._queue; } }
} }
// ReSharper restore UnusedMember.Local // ReSharper restore UnusedMember.Local
} }
} }

@ -186,6 +186,7 @@ namespace ZeroLevel.Services.Async
public IAsyncWaitQueue<IDisposable> WaitQueue { get { return _mutex._queue; } } public IAsyncWaitQueue<IDisposable> WaitQueue { get { return _mutex._queue; } }
} }
// ReSharper restore UnusedMember.Local // ReSharper restore UnusedMember.Local
} }
} }

@ -154,6 +154,7 @@ namespace ZeroLevel.Services.Async
public Task CurrentTask { get { return _mre._tcs.Task; } } public Task CurrentTask { get { return _mre._tcs.Task; } }
} }
// ReSharper restore UnusedMember.Local // ReSharper restore UnusedMember.Local
} }
} }

@ -82,6 +82,7 @@ namespace ZeroLevel.Services.Async
[DebuggerNonUserCode] [DebuggerNonUserCode]
internal int GetReaderCountForDebugger { get { return (_locksHeld > 0 ? _locksHeld : 0); } } internal int GetReaderCountForDebugger { get { return (_locksHeld > 0 ? _locksHeld : 0); } }
[DebuggerNonUserCode] [DebuggerNonUserCode]
internal bool GetUpgradeInProgressForDebugger { get { return !_upgradeReaderQueue.IsEmpty; } } internal bool GetUpgradeInProgressForDebugger { get { return !_upgradeReaderQueue.IsEmpty; } }
@ -764,6 +765,7 @@ namespace ZeroLevel.Services.Async
public IAsyncWaitQueue<IDisposable> UpgradeReaderWaitQueue { get { return _rwl._upgradeReaderQueue; } } public IAsyncWaitQueue<IDisposable> UpgradeReaderWaitQueue { get { return _rwl._upgradeReaderQueue; } }
} }
// ReSharper restore UnusedMember.Local // ReSharper restore UnusedMember.Local
} }
} }

@ -172,6 +172,7 @@ namespace ZeroLevel.Services.Async
public IAsyncWaitQueue<object> WaitQueue { get { return _semaphore._queue; } } public IAsyncWaitQueue<object> WaitQueue { get { return _semaphore._queue; } }
} }
// ReSharper restore UnusedMember.Local // ReSharper restore UnusedMember.Local
} }
} }

@ -1,8 +1,6 @@
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;

@ -248,7 +248,8 @@ namespace ZeroLevel.Services.Async
return this.GetEnumerator(); return this.GetEnumerator();
} }
#endregion #endregion GenericListImplementations
#region ObjectListImplementations #region ObjectListImplementations
int System.Collections.IList.Add(object value) int System.Collections.IList.Add(object value)
@ -329,7 +330,8 @@ namespace ZeroLevel.Services.Async
get { return this; } get { return this; }
} }
#endregion #endregion ObjectListImplementations
#region GenericListHelpers #region GenericListHelpers
/// <summary> /// <summary>
@ -386,7 +388,7 @@ namespace ZeroLevel.Services.Async
} }
} }
#endregion #endregion GenericListHelpers
/// <summary> /// <summary>
/// Gets a value indicating whether this instance is empty. /// Gets a value indicating whether this instance is empty.

@ -15,6 +15,7 @@ namespace ZeroLevel.Services.Async
/// </summary> /// </summary>
// ReSharper disable StaticFieldInGenericType // ReSharper disable StaticFieldInGenericType
private static int _lastId; private static int _lastId;
// ReSharper restore StaticFieldInGenericType // ReSharper restore StaticFieldInGenericType
/// <summary> /// <summary>

@ -75,6 +75,7 @@ namespace ZeroLevel.Services.Async
} }
return @this.TrySetResult(resultFunc()); return @this.TrySetResult(resultFunc());
} }
/// <summary> /// <summary>
/// Attempts to complete a <see cref="TaskCompletionSource{TResult}"/>, propagating the completion of <paramref name="eventArgs"/>. /// Attempts to complete a <see cref="TaskCompletionSource{TResult}"/>, propagating the completion of <paramref name="eventArgs"/>.
/// </summary> /// </summary>
@ -91,6 +92,7 @@ namespace ZeroLevel.Services.Async
return @this.TrySetException(eventArgs.Error); return @this.TrySetException(eventArgs.Error);
return @this.TrySetResult(getResult()); return @this.TrySetResult(getResult());
} }
/// <summary> /// <summary>
/// Attempts to complete a <see cref="TaskCompletionSource"/>, propagating the completion of <paramref name="task"/>. /// Attempts to complete a <see cref="TaskCompletionSource"/>, propagating the completion of <paramref name="task"/>.
/// </summary> /// </summary>
@ -105,6 +107,7 @@ namespace ZeroLevel.Services.Async
return @this.TrySetCanceled(); return @this.TrySetCanceled();
return @this.TrySetResult(); return @this.TrySetResult();
} }
/// <summary> /// <summary>
/// Attempts to complete a <see cref="TaskCompletionSource"/>, propagating the completion of <paramref name="eventArgs"/>. /// Attempts to complete a <see cref="TaskCompletionSource"/>, propagating the completion of <paramref name="eventArgs"/>.
/// </summary> /// </summary>
@ -119,6 +122,7 @@ namespace ZeroLevel.Services.Async
return @this.TrySetException(eventArgs.Error); return @this.TrySetException(eventArgs.Error);
return @this.TrySetResult(); return @this.TrySetResult();
} }
/// <summary> /// <summary>
/// Attempts to complete a <see cref="TaskCompletionSource{TResult}"/> with the specified value, forcing all continuations onto a threadpool thread even if they specified <c>ExecuteSynchronously</c>. /// Attempts to complete a <see cref="TaskCompletionSource{TResult}"/> with the specified value, forcing all continuations onto a threadpool thread even if they specified <c>ExecuteSynchronously</c>.
/// </summary> /// </summary>
@ -166,6 +170,7 @@ namespace ZeroLevel.Services.Async
{ {
} }
} }
/// <summary> /// <summary>
/// Creates a new TCS for use with async code, and which forces its continuations to execute asynchronously. /// Creates a new TCS for use with async code, and which forces its continuations to execute asynchronously.
/// </summary> /// </summary>
@ -174,6 +179,7 @@ namespace ZeroLevel.Services.Async
{ {
return new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously); return new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously);
} }
/// <summary> /// <summary>
/// Attempts to complete a <see cref="TaskCompletionSource"/> as canceled, forcing all continuations onto a threadpool thread even if they specified <c>ExecuteSynchronously</c>. /// Attempts to complete a <see cref="TaskCompletionSource"/> as canceled, forcing all continuations onto a threadpool thread even if they specified <c>ExecuteSynchronously</c>.
/// </summary> /// </summary>

@ -54,6 +54,7 @@ namespace ZeroLevel.Services.Async
using (var cancelTaskSource = new CancellationTokenTaskSource<TResult>(cancellationToken)) using (var cancelTaskSource = new CancellationTokenTaskSource<TResult>(cancellationToken))
return await await Task.WhenAny(task, cancelTaskSource.Task).ConfigureAwait(false); return await await Task.WhenAny(task, cancelTaskSource.Task).ConfigureAwait(false);
} }
/// <summary> /// <summary>
/// Waits for the task to complete, unwrapping any exceptions. /// Waits for the task to complete, unwrapping any exceptions.
/// </summary> /// </summary>

@ -68,6 +68,7 @@ namespace ZeroLevel.Services.Collections
return (T)_getter.Invoke(_instance, key); return (T)_getter.Invoke(_instance, key);
} }
} }
private readonly ConcurrentDictionary<Type, ConcreteTypeRepository> _shardedRepositories = private readonly ConcurrentDictionary<Type, ConcreteTypeRepository> _shardedRepositories =
new ConcurrentDictionary<Type, ConcreteTypeRepository>(); new ConcurrentDictionary<Type, ConcreteTypeRepository>();

@ -22,6 +22,7 @@ namespace ZeroLevel.Services.Collections
_nextIndex = 0; _nextIndex = 0;
_count = 0; _count = 0;
} }
/// <summary> /// <summary>
/// If count is limited when intem adding, oldest item replace with new item /// If count is limited when intem adding, oldest item replace with new item
/// </summary> /// </summary>

@ -3,11 +3,17 @@
public interface IEverythingStorage public interface IEverythingStorage
{ {
bool TryAdd<T>(string key, T value); bool TryAdd<T>(string key, T value);
bool ContainsKey<T>(string key); bool ContainsKey<T>(string key);
bool TryRemove<T>(string key); bool TryRemove<T>(string key);
void Add<T>(string key, T value); void Add<T>(string key, T value);
void AddOrUpdate<T>(string key, T value); void AddOrUpdate<T>(string key, T value);
void Remove<T>(string key); void Remove<T>(string key);
T Get<T>(string key); T Get<T>(string key);
} }
} }

@ -5,10 +5,15 @@ namespace ZeroLevel.Services.Collections
public interface IFixSizeQueue<T> public interface IFixSizeQueue<T>
{ {
void Push(T item); void Push(T item);
long Count { get; } long Count { get; }
bool TryTake(out T t); bool TryTake(out T t);
T Take(); T Take();
IEnumerable<T> Dump(); IEnumerable<T> Dump();
bool Contains(T item, IComparer<T> comparer = null); bool Contains(T item, IComparer<T> comparer = null);
} }
} }

@ -15,7 +15,9 @@ namespace ZeroLevel.Services.Collections
{ {
private readonly List<T> _collection = private readonly List<T> _collection =
new List<T>(); new List<T>();
private int _index = -1; private int _index = -1;
private readonly ReaderWriterLockSlim _lock = private readonly ReaderWriterLockSlim _lock =
new ReaderWriterLockSlim(); new ReaderWriterLockSlim();

@ -14,19 +14,24 @@ namespace ZeroLevel.Services.Config
IConfiguration IConfiguration
{ {
#region Private members #region Private members
/// <summary> /// <summary>
/// When true, any changes disallow /// When true, any changes disallow
/// </summary> /// </summary>
private bool _freezed = false; private bool _freezed = false;
/// <summary> /// <summary>
/// When true, freeze permanent, can't be canceled /// When true, freeze permanent, can't be canceled
/// </summary> /// </summary>
private bool _permanentFreezed = false; private bool _permanentFreezed = false;
private readonly object _freezeLock = new object(); private readonly object _freezeLock = new object();
/// <summary> /// <summary>
/// Key-values dictionary /// Key-values dictionary
/// </summary> /// </summary>
private readonly ConcurrentDictionary<string, IList<string>> _keyValues = new ConcurrentDictionary<string, IList<string>>(); private readonly ConcurrentDictionary<string, IList<string>> _keyValues = new ConcurrentDictionary<string, IList<string>>();
/// <summary> /// <summary>
/// Empty list /// Empty list
/// </summary> /// </summary>
@ -40,9 +45,11 @@ namespace ZeroLevel.Services.Config
} }
return key.Trim().ToLower(CultureInfo.InvariantCulture); return key.Trim().ToLower(CultureInfo.InvariantCulture);
} }
#endregion
#endregion Private members
#region Properties #region Properties
/// <summary> /// <summary>
/// Get values by key /// Get values by key
/// </summary> /// </summary>
@ -61,6 +68,7 @@ namespace ZeroLevel.Services.Config
return EmptyValuesList; return EmptyValuesList;
} }
} }
/// <summary> /// <summary>
/// Keys list /// Keys list
/// </summary> /// </summary>
@ -76,11 +84,13 @@ namespace ZeroLevel.Services.Config
return _freezed; return _freezed;
} }
} }
#endregion
#endregion Properties
#region Public methods #region Public methods
#region Get #region Get
/// <summary> /// <summary>
/// Получение списка значение соотвествующих указанному ключу /// Получение списка значение соотвествующих указанному ключу
/// </summary> /// </summary>
@ -90,6 +100,7 @@ namespace ZeroLevel.Services.Config
{ {
return this[key]; return this[key];
} }
/// <summary> /// <summary>
/// Получение первого значения для указанного ключа /// Получение первого значения для указанного ключа
/// </summary> /// </summary>
@ -140,6 +151,7 @@ namespace ZeroLevel.Services.Config
} }
throw new KeyNotFoundException("Parameter not found: " + key); throw new KeyNotFoundException("Parameter not found: " + key);
} }
/// <summary> /// <summary>
/// Получение первого значения для указанного ключа, или значения по умолчанию /// Получение первого значения для указанного ключа, или значения по умолчанию
/// </summary> /// </summary>
@ -156,6 +168,7 @@ namespace ZeroLevel.Services.Config
} }
return defaultValue; return defaultValue;
} }
/// <summary> /// <summary>
/// Получение первого значения для указанного ключа, или значения по умолчанию, с попыткой преобразования в указанный тип /// Получение первого значения для указанного ключа, или значения по умолчанию, с попыткой преобразования в указанный тип
/// </summary> /// </summary>
@ -172,6 +185,7 @@ namespace ZeroLevel.Services.Config
} }
return default(T); return default(T);
} }
/// <summary> /// <summary>
/// Получение первого значения для указанного ключа, или значения по умолчанию, с попыткой преобразования в указанный тип /// Получение первого значения для указанного ключа, или значения по умолчанию, с попыткой преобразования в указанный тип
/// </summary> /// </summary>
@ -189,6 +203,7 @@ namespace ZeroLevel.Services.Config
} }
return defaultValue; return defaultValue;
} }
/// <summary> /// <summary>
/// Проверка наличия ключа и непустого списка связанных с ним значений /// Проверка наличия ключа и непустого списка связанных с ним значений
/// </summary> /// </summary>
@ -199,6 +214,7 @@ namespace ZeroLevel.Services.Config
key = GetKey(key); key = GetKey(key);
return _keyValues.ContainsKey(key) && _keyValues[key].Count > 0; return _keyValues.ContainsKey(key) && _keyValues[key].Count > 0;
} }
/// <summary> /// <summary>
/// Проверка наличия одного из ключей /// Проверка наличия одного из ключей
/// </summary> /// </summary>
@ -208,6 +224,7 @@ namespace ZeroLevel.Services.Config
if (Contains(key)) return true; if (Contains(key)) return true;
return false; return false;
} }
/// <summary> /// <summary>
/// Проверка наличия ключа и связанного с ним значения /// Проверка наличия ключа и связанного с ним значения
/// </summary> /// </summary>
@ -223,6 +240,7 @@ namespace ZeroLevel.Services.Config
} }
return false; return false;
} }
/// <summary> /// <summary>
/// Количество значений связанных с указанным ключом /// Количество значений связанных с указанным ключом
/// </summary> /// </summary>
@ -237,7 +255,8 @@ namespace ZeroLevel.Services.Config
} }
return 0; return 0;
} }
#endregion
#endregion Get
/// <summary> /// <summary>
/// Add key-value /// Add key-value
@ -257,6 +276,7 @@ namespace ZeroLevel.Services.Config
} }
return this; return this;
} }
/// <summary> /// <summary>
/// Set unique value for key /// Set unique value for key
/// </summary> /// </summary>
@ -277,6 +297,7 @@ namespace ZeroLevel.Services.Config
} }
return this; return this;
} }
/// <summary> /// <summary>
/// Clean values binded with key /// Clean values binded with key
/// </summary> /// </summary>
@ -293,6 +314,7 @@ namespace ZeroLevel.Services.Config
} }
return this; return this;
} }
/// <summary> /// <summary>
/// Configuration drop /// Configuration drop
/// </summary> /// </summary>
@ -304,6 +326,7 @@ namespace ZeroLevel.Services.Config
} }
return this; return this;
} }
/// <summary> /// <summary>
/// Remove key and binded values /// Remove key and binded values
/// </summary> /// </summary>
@ -349,9 +372,11 @@ namespace ZeroLevel.Services.Config
return false; return false;
} }
} }
#endregion
#endregion Public methods
#region IEquatable #region IEquatable
public bool Equals(IConfiguration other) public bool Equals(IConfiguration other)
{ {
if (other == null) if (other == null)
@ -371,9 +396,11 @@ namespace ZeroLevel.Services.Config
} }
return true; return true;
} }
#endregion
#endregion IEquatable
#region Binary Serializable #region Binary Serializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteBoolean(this._freezed); writer.WriteBoolean(this._freezed);
@ -408,6 +435,7 @@ namespace ZeroLevel.Services.Config
_keyValues.TryAdd(key, list_values); _keyValues.TryAdd(key, list_values);
} }
} }
#endregion
#endregion Binary Serializable
} }
} }

@ -13,6 +13,7 @@ namespace ZeroLevel.Services.Config
IConfigurationSet IConfigurationSet
{ {
#region Private members #region Private members
/// <summary> /// <summary>
/// Sections /// Sections
/// </summary> /// </summary>
@ -26,9 +27,11 @@ namespace ZeroLevel.Services.Config
} }
return key.Trim().ToLower(CultureInfo.InvariantCulture); return key.Trim().ToLower(CultureInfo.InvariantCulture);
} }
#endregion
#endregion Private members
#region Properties #region Properties
public IConfiguration Default public IConfiguration Default
{ {
get { return _sections[Configuration.DEFAULT_SECTION_NAME]; } get { return _sections[Configuration.DEFAULT_SECTION_NAME]; }
@ -60,9 +63,10 @@ namespace ZeroLevel.Services.Config
} }
} }
#endregion #endregion Properties
#region Methods #region Methods
public BaseConfigurationSet() public BaseConfigurationSet()
{ {
CreateSection(Configuration.DEFAULT_SECTION_NAME); CreateSection(Configuration.DEFAULT_SECTION_NAME);
@ -119,18 +123,22 @@ namespace ZeroLevel.Services.Config
} }
return false; return false;
} }
#endregion
#endregion Methods
#region IEquatable #region IEquatable
public bool Equals(IConfigurationSet other) public bool Equals(IConfigurationSet other)
{ {
if (other == null) return false; if (other == null) return false;
return this.SectionNames.NoOrderingEquals(other.SectionNames) && return this.SectionNames.NoOrderingEquals(other.SectionNames) &&
this.Sections.NoOrderingEquals(other.Sections); this.Sections.NoOrderingEquals(other.Sections);
} }
#endregion
#endregion IEquatable
#region Freezing #region Freezing
private readonly object _freezeLock = new object(); private readonly object _freezeLock = new object();
public bool FreezeConfiguration(bool permanent = false) public bool FreezeConfiguration(bool permanent = false)
@ -193,9 +201,11 @@ namespace ZeroLevel.Services.Config
return false; return false;
} }
} }
#endregion
#endregion Freezing
#region Binary Serializable #region Binary Serializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteBoolean(this._sectionsFreezed); writer.WriteBoolean(this._sectionsFreezed);
@ -220,6 +230,7 @@ namespace ZeroLevel.Services.Config
_sections.TryAdd(key, reader.Read<BaseConfiguration>()); _sections.TryAdd(key, reader.Read<BaseConfiguration>());
} }
} }
#endregion
#endregion Binary Serializable
} }
} }

@ -23,6 +23,7 @@ namespace ZeroLevel
public const string DEFAULT_SECTION_NAME = "_defaultsection"; public const string DEFAULT_SECTION_NAME = "_defaultsection";
#region Ctor #region Ctor
static Configuration() static Configuration()
{ {
_empty = new BaseConfiguration(); _empty = new BaseConfiguration();
@ -30,9 +31,11 @@ namespace ZeroLevel
_empty.Freeze(true); _empty.Freeze(true);
_emptySet.FreezeConfiguration(true); _emptySet.FreezeConfiguration(true);
} }
#endregion
#endregion Ctor
#region Cachee #region Cachee
private static readonly IConfiguration _empty; private static readonly IConfiguration _empty;
private static readonly IConfigurationSet _emptySet; private static readonly IConfigurationSet _emptySet;
private static readonly ConcurrentDictionary<string, IConfiguration> _cachee = new ConcurrentDictionary<string, IConfiguration>(); private static readonly ConcurrentDictionary<string, IConfiguration> _cachee = new ConcurrentDictionary<string, IConfiguration>();
@ -97,9 +100,11 @@ namespace ZeroLevel
} }
return result; return result;
} }
#endregion
#endregion Cachee
#region Factory #region Factory
public static IConfiguration Create() public static IConfiguration Create()
{ {
return new BaseConfiguration(); return new BaseConfiguration();
@ -114,41 +119,49 @@ namespace ZeroLevel
{ {
return new BaseConfigurationSet(defaultConfiguration); return new BaseConfigurationSet(defaultConfiguration);
} }
#endregion
#endregion Factory
#region Read configuration #region Read configuration
/// <summary> /// <summary>
/// Создание конфигурации из секции AppSettings файла app.config или web.config /// Создание конфигурации из секции AppSettings файла app.config или web.config
/// </summary> /// </summary>
/// <returns>Конфигурация</returns> /// <returns>Конфигурация</returns>
public static IConfiguration ReadFromApplicationConfig() { return new ApplicationConfigReader().ReadConfiguration(); } public static IConfiguration ReadFromApplicationConfig() { return new ApplicationConfigReader().ReadConfiguration(); }
/// <summary> /// <summary>
/// Создание конфигурации из секции AppSettings файла app.config или web.config, дополняется секцией 'ConnectionStrings' /// Создание конфигурации из секции AppSettings файла app.config или web.config, дополняется секцией 'ConnectionStrings'
/// </summary> /// </summary>
/// <returns>Конфигурация</returns> /// <returns>Конфигурация</returns>
public static IConfigurationSet ReadSetFromApplicationConfig() { return new ApplicationConfigReader().ReadConfigurationSet(); } public static IConfigurationSet ReadSetFromApplicationConfig() { return new ApplicationConfigReader().ReadConfigurationSet(); }
/// <summary> /// <summary>
/// Создание конфигурации из секции AppSettings файла app.config или web.config /// Создание конфигурации из секции AppSettings файла app.config или web.config
/// </summary> /// </summary>
/// <returns>Конфигурация</returns> /// <returns>Конфигурация</returns>
public static IConfiguration ReadFromApplicationConfig(string configFilePath) { return new ApplicationConfigReader(configFilePath).ReadConfiguration(); } public static IConfiguration ReadFromApplicationConfig(string configFilePath) { return new ApplicationConfigReader(configFilePath).ReadConfiguration(); }
/// <summary> /// <summary>
/// Создание конфигурации из секции AppSettings файла app.config или web.config, дополняется секцией 'ConnectionStrings' /// Создание конфигурации из секции AppSettings файла app.config или web.config, дополняется секцией 'ConnectionStrings'
/// </summary> /// </summary>
/// <returns>Конфигурация</returns> /// <returns>Конфигурация</returns>
public static IConfigurationSet ReadSetFromApplicationConfig(string configFilePath) { return new ApplicationConfigReader(configFilePath).ReadConfigurationSet(); } public static IConfigurationSet ReadSetFromApplicationConfig(string configFilePath) { return new ApplicationConfigReader(configFilePath).ReadConfigurationSet(); }
/// <summary> /// <summary>
/// Создание конфигурации из ini файла /// Создание конфигурации из ini файла
/// </summary> /// </summary>
/// <param name="path">Путь к ini-файлу</param> /// <param name="path">Путь к ini-файлу</param>
/// <returns>Конфигурация</returns> /// <returns>Конфигурация</returns>
public static IConfiguration ReadFromIniFile(string path) { return new IniFileReader(path).ReadConfiguration(); } public static IConfiguration ReadFromIniFile(string path) { return new IniFileReader(path).ReadConfiguration(); }
/// <summary> /// <summary>
/// Создание конфигурации из ini файла, с учетом секций /// Создание конфигурации из ini файла, с учетом секций
/// </summary> /// </summary>
/// <param name="path">Путь к ini-файлу</param> /// <param name="path">Путь к ini-файлу</param>
/// <returns>Конфигурация</returns> /// <returns>Конфигурация</returns>
public static IConfigurationSet ReadSetFromIniFile(string path) { return new IniFileReader(path).ReadConfigurationSet(); } public static IConfigurationSet ReadSetFromIniFile(string path) { return new IniFileReader(path).ReadConfigurationSet(); }
/// <summary> /// <summary>
/// Создание конфигурации из параметров командной строки /// Создание конфигурации из параметров командной строки
/// </summary> /// </summary>
@ -156,22 +169,29 @@ namespace ZeroLevel
/// <returns>Конфигурация</returns> /// <returns>Конфигурация</returns>
public static IConfiguration ReadFromCommandLine(string[] args) { return new CommandLineReader(args).ReadConfiguration(); } public static IConfiguration ReadFromCommandLine(string[] args) { return new CommandLineReader(args).ReadConfiguration(); }
public static IConfigurationSet ReadBinary(IBinaryReader reader) { return reader.Read<BaseConfigurationSet>(); } public static IConfigurationSet ReadBinary(IBinaryReader reader)
#endregion {
return reader.Read<BaseConfigurationSet>();
}
#endregion Read configuration
#region Write configuration #region Write configuration
/// <summary> /// <summary>
/// Запись простой конфигурации в ini-файл /// Запись простой конфигурации в ini-файл
/// </summary> /// </summary>
/// <param name="configuration">Конфигурация</param> /// <param name="configuration">Конфигурация</param>
/// <param name="path">Путь к ini-файлу</param> /// <param name="path">Путь к ini-файлу</param>
public static void WriteToIniFile(IConfiguration configuration, string path) { new IniFileWriter(path).WriteConfiguration(configuration); } public static void WriteToIniFile(IConfiguration configuration, string path) { new IniFileWriter(path).WriteConfiguration(configuration); }
/// <summary> /// <summary>
/// Запись полной конфигурации в ini-файл /// Запись полной конфигурации в ini-файл
/// </summary> /// </summary>
/// <param name="configuration">Конфигурация</param> /// <param name="configuration">Конфигурация</param>
/// <param name="path">Путь к ini-файлу</param> /// <param name="path">Путь к ini-файлу</param>
public static void WriteSetToIniFile(IConfigurationSet configuration, string path) { new IniFileWriter(path).WriteConfigurationSet(configuration); } public static void WriteSetToIniFile(IConfigurationSet configuration, string path) { new IniFileWriter(path).WriteConfigurationSet(configuration); }
#endregion
#endregion Write configuration
} }
} }

@ -12,103 +12,128 @@ namespace ZeroLevel
IBinarySerializable IBinarySerializable
{ {
#region Properties #region Properties
/// <summary> /// <summary>
/// Get values by key /// Get values by key
/// </summary> /// </summary>
IEnumerable<string> this[string key] { get; } IEnumerable<string> this[string key] { get; }
/// <summary> /// <summary>
/// Keys /// Keys
/// </summary> /// </summary>
IEnumerable<string> Keys { get; } IEnumerable<string> Keys { get; }
/// <summary> /// <summary>
/// Configuration is locked for change when true /// Configuration is locked for change when true
/// </summary> /// </summary>
bool Freezed { get; } bool Freezed { get; }
#endregion
#endregion Properties
#region Methods #region Methods
/// <summary> /// <summary>
/// Get values by key /// Get values by key
/// </summary> /// </summary>
/// <param name="key">Key</param> /// <param name="key">Key</param>
/// <returns>Values list</returns> /// <returns>Values list</returns>
IEnumerable<string> Items(string key); IEnumerable<string> Items(string key);
/// <summary> /// <summary>
/// Get first value by key /// Get first value by key
/// </summary> /// </summary>
string First(string key); string First(string key);
/// <summary> /// <summary>
/// Get first value by key with cast to <typeparamref name="T"/> /// Get first value by key with cast to <typeparamref name="T"/>
/// </summary> /// </summary>
T First<T>(string key); T First<T>(string key);
/// <summary> /// <summary>
/// Get first or default value by key /// Get first or default value by key
/// </summary> /// </summary>
string FirstOrDefault(string name, string defaultValue); string FirstOrDefault(string name, string defaultValue);
/// <summary> /// <summary>
/// Get first or default value by key with cast to <typeparamref name="T"/> /// Get first or default value by key with cast to <typeparamref name="T"/>
/// </summary> /// </summary>
T FirstOrDefault<T>(string name); T FirstOrDefault<T>(string name);
/// <summary> /// <summary>
/// Get first or default value by key with cast to <typeparamref name="T"/> /// Get first or default value by key with cast to <typeparamref name="T"/>
/// </summary> /// </summary>
T FirstOrDefault<T>(string name, T defaultValue); T FirstOrDefault<T>(string name, T defaultValue);
/// <summary> /// <summary>
/// Check key exists /// Check key exists
/// </summary> /// </summary>
bool Contains(string key); bool Contains(string key);
/// <summary> /// <summary>
/// Check one of key exists /// Check one of key exists
/// </summary> /// </summary>
bool Contains(params string[] keys); bool Contains(params string[] keys);
/// <summary> /// <summary>
/// true if exists one or more values by key /// true if exists one or more values by key
/// </summary> /// </summary>
bool ContainsValue(string key, string value); bool ContainsValue(string key, string value);
/// <summary> /// <summary>
/// Count values by key /// Count values by key
/// </summary> /// </summary>
int Count(string key); int Count(string key);
/// <summary> /// <summary>
/// Do action if key exists, action takes first value /// Do action if key exists, action takes first value
/// </summary> /// </summary>
void DoWithFirst(string key, Action<string> action); void DoWithFirst(string key, Action<string> action);
/// <summary> /// <summary>
/// Do action if key exists, action takes first value with cast to <typeparamref name="T"/> /// Do action if key exists, action takes first value with cast to <typeparamref name="T"/>
/// </summary> /// </summary>
void DoWithFirst<T>(string key, Action<T> action); void DoWithFirst<T>(string key, Action<T> action);
#endregion
#endregion Methods
#region Create, Clean, Delete #region Create, Clean, Delete
/// <summary> /// <summary>
/// Clean /// Clean
/// </summary> /// </summary>
IConfiguration Clear(); IConfiguration Clear();
/// <summary> /// <summary>
/// Clean values by key /// Clean values by key
/// </summary> /// </summary>
IConfiguration Clear(string key); IConfiguration Clear(string key);
/// <summary> /// <summary>
/// Remove key and binded values /// Remove key and binded values
/// </summary> /// </summary>
IConfiguration Remove(string key); IConfiguration Remove(string key);
/// <summary> /// <summary>
/// Append key and value /// Append key and value
/// </summary> /// </summary>
IConfiguration Append(string key, string value); IConfiguration Append(string key, string value);
/// <summary> /// <summary>
/// Set key with one value, if any values by key exists, they will be dropped /// Set key with one value, if any values by key exists, they will be dropped
/// </summary> /// </summary>
IConfiguration SetUnique(string key, string value); IConfiguration SetUnique(string key, string value);
/// <summary> /// <summary>
/// Sets a prohibition on changing /// Sets a prohibition on changing
/// </summary> /// </summary>
/// <returns>false - prohibition was set already</returns> /// <returns>false - prohibition was set already</returns>
bool Freeze(bool permanent = false); bool Freeze(bool permanent = false);
/// <summary> /// <summary>
/// Remove a prohibition on changing /// Remove a prohibition on changing
/// </summary> /// </summary>
bool Unfreeze(); bool Unfreeze();
#endregion
#endregion Create, Clean, Delete
} }
} }

@ -3,6 +3,7 @@
public interface IConfigurationReader public interface IConfigurationReader
{ {
IConfiguration ReadConfiguration(); IConfiguration ReadConfiguration();
IConfigurationSet ReadConfigurationSet(); IConfigurationSet ReadConfigurationSet();
} }
} }

@ -12,66 +12,81 @@ namespace ZeroLevel
IBinarySerializable IBinarySerializable
{ {
#region Properties #region Properties
/// <summary> /// <summary>
/// Default section, always exists /// Default section, always exists
/// </summary> /// </summary>
IConfiguration Default { get; } IConfiguration Default { get; }
/// <summary> /// <summary>
/// Get configuration section by name /// Get configuration section by name
/// </summary> /// </summary>
IConfiguration this[string sectionName] { get; } IConfiguration this[string sectionName] { get; }
/// <summary> /// <summary>
/// Get configuration section names /// Get configuration section names
/// </summary> /// </summary>
IEnumerable<string> SectionNames { get; } IEnumerable<string> SectionNames { get; }
/// <summary> /// <summary>
/// Get all sections /// Get all sections
/// </summary> /// </summary>
IEnumerable<IConfiguration> Sections { get; } IEnumerable<IConfiguration> Sections { get; }
/// <summary> /// <summary>
/// true if changing disallow /// true if changing disallow
/// </summary> /// </summary>
bool SectionsFreezed { get; } bool SectionsFreezed { get; }
#endregion
#endregion Properties
#region Methods #region Methods
/// <summary> /// <summary>
/// Create section /// Create section
/// </summary> /// </summary>
/// <param name="sectionName">Section name</param> /// <param name="sectionName">Section name</param>
IConfiguration CreateSection(string sectionName); IConfiguration CreateSection(string sectionName);
/// <summary> /// <summary>
/// Get configuration section by name /// Get configuration section by name
/// </summary> /// </summary>
/// <param name="sectionName">Название секции</param> /// <param name="sectionName">Название секции</param>
/// <returns>Секция с данными</returns> /// <returns>Секция с данными</returns>
IConfiguration GetSection(string sectionName); IConfiguration GetSection(string sectionName);
/// <summary> /// <summary>
/// Check for a section by name /// Check for a section by name
/// </summary> /// </summary>
/// <param name="sectionName">Section name</param> /// <param name="sectionName">Section name</param>
bool ContainsSection(string sectionName); bool ContainsSection(string sectionName);
/// <summary>Remove section by name /// <summary>Remove section by name
/// </summary> /// </summary>
/// <param name="sectionName">Section name</param> /// <param name="sectionName">Section name</param>
bool RemoveSection(string sectionName); bool RemoveSection(string sectionName);
/// <summary> /// <summary>
/// Sets a prohibition on changing configurations /// Sets a prohibition on changing configurations
/// </summary> /// </summary>
bool FreezeConfiguration(bool permanent = false); bool FreezeConfiguration(bool permanent = false);
/// <summary> /// <summary>
/// Sets a prohibition on changing sections /// Sets a prohibition on changing sections
/// </summary> /// </summary>
bool FreezeSections(bool permanent = false); bool FreezeSections(bool permanent = false);
/// <summary> /// <summary>
/// Remove a prohibition on changing configurations /// Remove a prohibition on changing configurations
/// </summary> /// </summary>
/// <returns>false - если запрет снят</returns> /// <returns>false - если запрет снят</returns>
bool UnfreezeConfiguration(); bool UnfreezeConfiguration();
/// <summary> /// <summary>
/// Sets a prohibition on changing sections /// Sets a prohibition on changing sections
/// </summary> /// </summary>
bool UnfreezeSections(); bool UnfreezeSections();
#endregion
#endregion Methods
} }
} }

@ -3,6 +3,7 @@
public interface IConfigurationWriter public interface IConfigurationWriter
{ {
void WriteConfiguration(IConfiguration configuration); void WriteConfiguration(IConfiguration configuration);
void WriteConfigurationSet(IConfigurationSet configuration); void WriteConfigurationSet(IConfigurationSet configuration);
} }
} }

@ -5,8 +5,15 @@
{ {
private readonly AppWebConfigReader _reader; private readonly AppWebConfigReader _reader;
internal ApplicationConfigReader() { _reader = new AppWebConfigReader(); } internal ApplicationConfigReader()
internal ApplicationConfigReader(string configFilePath) { _reader = new AppWebConfigReader(configFilePath); } {
_reader = new AppWebConfigReader();
}
internal ApplicationConfigReader(string configFilePath)
{
_reader = new AppWebConfigReader(configFilePath);
}
public IConfiguration ReadConfiguration() public IConfiguration ReadConfiguration()
{ {

@ -17,6 +17,7 @@ namespace ZeroLevel.Services.Config.Implementation
{ {
_iniPath = iniPath; _iniPath = iniPath;
} }
/// <summary> /// <summary>
/// Write config to file /// Write config to file
/// </summary> /// </summary>
@ -41,6 +42,7 @@ namespace ZeroLevel.Services.Config.Implementation
writer.Flush(); writer.Flush();
} }
} }
/// <summary> /// <summary>
/// Write configuration set to file /// Write configuration set to file
/// </summary> /// </summary>

@ -6,41 +6,62 @@ namespace ZeroLevel.DocumentObjectModel
{ {
// Primitives // Primitives
void ReadText(Text text); void ReadText(Text text);
void ReadQuote(Quote quote); void ReadQuote(Quote quote);
void ReadLink(Link link, int order); void ReadLink(Link link, int order);
void ReadImage(Image image, int order); void ReadImage(Image image, int order);
void ReadAudio(Audio audio, int order); void ReadAudio(Audio audio, int order);
void ReadVideo(Video video, int order); void ReadVideo(Video video, int order);
// Containers // Containers
void EnterSection(Section section); void EnterSection(Section section);
void LeaveSection(Section section); void LeaveSection(Section section);
void EnterParagraph(Paragraph paragraph); void EnterParagraph(Paragraph paragraph);
void LeaveParagraph(Paragraph paragraph); void LeaveParagraph(Paragraph paragraph);
void EnterList(List list); void EnterList(List list);
void EnterListItem(List list, IContentElement item, int order); void EnterListItem(List list, IContentElement item, int order);
void LeaveListItem(List list, IContentElement item, int order); void LeaveListItem(List list, IContentElement item, int order);
void LeaveList(List list); void LeaveList(List list);
void EnterTable(Table table); void EnterTable(Table table);
void EnterColumns(Table table); void EnterColumns(Table table);
void ReadColumn(Table table, Column column, int order); void ReadColumn(Table table, Column column, int order);
void LeaveColumns(Table table); void LeaveColumns(Table table);
void EnterRow(Table table, Row row, int order); void EnterRow(Table table, Row row, int order);
void EnterRowCell(Table table, Row row, IContentElement cell, int order); void EnterRowCell(Table table, Row row, IContentElement cell, int order);
void LeaveRowCell(Table table, Row row, IContentElement cell, int order); void LeaveRowCell(Table table, Row row, IContentElement cell, int order);
void LeaveRow(Table table, Row row, int order); void LeaveRow(Table table, Row row, int order);
void LeaveTable(Table table); void LeaveTable(Table table);
void EnterGallery(Gallery gallery); void EnterGallery(Gallery gallery);
void LeaveGallery(Gallery gallery); void LeaveGallery(Gallery gallery);
void EnterAudioplayer(Audioplayer player); void EnterAudioplayer(Audioplayer player);
void LeaveAudioplayer(Audioplayer player); void LeaveAudioplayer(Audioplayer player);
void EnterVideoplayer(Videoplayer player); void EnterVideoplayer(Videoplayer player);
void LeaveVideoplayer(Videoplayer player); void LeaveVideoplayer(Videoplayer player);
// Feature // Feature

@ -6,54 +6,91 @@ namespace ZeroLevel.DocumentObjectModel
public interface IMetadataReader<T> public interface IMetadataReader<T>
{ {
void ReadId(Guid Id); void ReadId(Guid Id);
void ReadSummary(string summary); void ReadSummary(string summary);
void ReadHeader(string header); void ReadHeader(string header);
void EnterIdentifier(Identifier identifier); void EnterIdentifier(Identifier identifier);
void ReadVersion(int version); void ReadVersion(int version);
void ReadTimestamp(long timestamp); void ReadTimestamp(long timestamp);
void ReadDateLabel(string datelabel); void ReadDateLabel(string datelabel);
void LeaveIdentifier(Identifier identifier); void LeaveIdentifier(Identifier identifier);
void EnterTagsBlock(TagMetadata tagBlock); void EnterTagsBlock(TagMetadata tagBlock);
void EnterKeywords(IEnumerable<string> keywords); void EnterKeywords(IEnumerable<string> keywords);
void ReadKeyword(string keyword, int order); void ReadKeyword(string keyword, int order);
void LeaveKeywords(IEnumerable<string> keywords); void LeaveKeywords(IEnumerable<string> keywords);
void EnterPlaces(IEnumerable<Tag> places); void EnterPlaces(IEnumerable<Tag> places);
void ReadPlace(Tag place, int order); void ReadPlace(Tag place, int order);
void LeavePlaces(IEnumerable<Tag> places); void LeavePlaces(IEnumerable<Tag> places);
void EnterCompanies(IEnumerable<Tag> companies); void EnterCompanies(IEnumerable<Tag> companies);
void ReadCompany(Tag company, int order); void ReadCompany(Tag company, int order);
void LeaveCompanies(IEnumerable<Tag> companies); void LeaveCompanies(IEnumerable<Tag> companies);
void EnterPersons(IEnumerable<Tag> persons); void EnterPersons(IEnumerable<Tag> persons);
void ReadPerson(Tag person, int order); void ReadPerson(Tag person, int order);
void LeavePersons(IEnumerable<Tag> persons); void LeavePersons(IEnumerable<Tag> persons);
void LeaveTagsBlock(TagMetadata tagBlock); void LeaveTagsBlock(TagMetadata tagBlock);
void EnterDescriptioveBlock(DescriptiveMetadata metadata); void EnterDescriptioveBlock(DescriptiveMetadata metadata);
void ReadAuthors(string byline); void ReadAuthors(string byline);
void ReadCopiright(string copyright); void ReadCopiright(string copyright);
void ReadCreated(DateTime created); void ReadCreated(DateTime created);
void ReadLanguage(string language); void ReadLanguage(string language);
void ReadPriority(Priority priority); void ReadPriority(Priority priority);
void ReadSource(Agency source); void ReadSource(Agency source);
void ReadPublisher(Agency publisher); void ReadPublisher(Agency publisher);
void ReadOriginal(Tag original); void ReadOriginal(Tag original);
void EnterHeaders(IEnumerable<Header> headers); void EnterHeaders(IEnumerable<Header> headers);
void ReadHeader(Header header, int order); void ReadHeader(Header header, int order);
void LeaveHeaders(IEnumerable<Header> headers); void LeaveHeaders(IEnumerable<Header> headers);
void LeaveDescriptioveBlock(DescriptiveMetadata metadata); void LeaveDescriptioveBlock(DescriptiveMetadata metadata);
void EnterAsides(IEnumerable<AttachContent> asides); void EnterAsides(IEnumerable<AttachContent> asides);
void ReadAside(AttachContent aside, int order); void ReadAside(AttachContent aside, int order);
void LeaveAsides(IEnumerable<AttachContent> asides); void LeaveAsides(IEnumerable<AttachContent> asides);
void EnterAssotiations(IEnumerable<Assotiation> assotiations); void EnterAssotiations(IEnumerable<Assotiation> assotiations);
void ReadAssotiation(Assotiation assotiation, int order); void ReadAssotiation(Assotiation assotiation, int order);
void LeaveAssotiations(IEnumerable<Assotiation> assotiations); void LeaveAssotiations(IEnumerable<Assotiation> assotiations);
void EnterCategories(IEnumerable<Category> categories); void EnterCategories(IEnumerable<Category> categories);
void ReadCategory(Category category, int order); void ReadCategory(Category category, int order);
void LeaveCategories(IEnumerable<Category> categories); void LeaveCategories(IEnumerable<Category> categories);
T Complete(); T Complete();

@ -22,6 +22,7 @@ namespace DOM.DSL.Contexts
}; };
public TContext ParentContext { get; protected set; } public TContext ParentContext { get; protected set; }
public abstract void Read(TStringReader reader); public abstract void Read(TStringReader reader);
} }
} }

@ -1,10 +1,10 @@
using System; using DOM.DSL.Model;
using System.Linq; using DOM.DSL.Services;
using DOM.DSL.Tokens;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
using DOM.DSL.Tokens;
using DOM.DSL.Services;
using DOM.DSL.Model;
namespace DOM.DSL.Contexts namespace DOM.DSL.Contexts
{ {
@ -47,6 +47,7 @@ namespace DOM.DSL.Contexts
switch (reader.Current) switch (reader.Current)
{ {
#region Ecsaping #region Ecsaping
case TChar.Escape: case TChar.Escape:
{ {
switch (reader.Next) switch (reader.Next)
@ -55,18 +56,22 @@ namespace DOM.DSL.Contexts
text.Append(' '); text.Append(' ');
reader.Move(2); reader.Move(2);
break; break;
case 'r': case 'r':
text.Append(TChar.CaretReturn); text.Append(TChar.CaretReturn);
reader.Move(2); reader.Move(2);
break; break;
case 'n': case 'n':
text.Append(TChar.Newline); text.Append(TChar.Newline);
reader.Move(2); reader.Move(2);
break; break;
case 't': case 't':
text.Append(TChar.Tab); text.Append(TChar.Tab);
reader.Move(2); reader.Move(2);
break; break;
case '@': case '@':
case '(': case '(':
case ')': case ')':
@ -76,6 +81,7 @@ namespace DOM.DSL.Contexts
text.Append(reader.Next); text.Append(reader.Next);
reader.Move(2); reader.Move(2);
break; break;
default: default:
text.Append(reader.Current); text.Append(reader.Current);
reader.Move(); reader.Move();
@ -83,7 +89,8 @@ namespace DOM.DSL.Contexts
} }
} }
break; break;
#endregion
#endregion Ecsaping
case TChar.FuncArgsEnd: case TChar.FuncArgsEnd:
{ {
@ -162,6 +169,7 @@ namespace DOM.DSL.Contexts
} }
} }
break; break;
default: default:
{ {
text.Append(reader.Current); text.Append(reader.Current);

@ -69,6 +69,7 @@ namespace DOM.DSL.Contexts
switch (reader.Current) switch (reader.Current)
{ {
#region Ecsaping #region Ecsaping
case TChar.Escape: case TChar.Escape:
{ {
switch (reader.Next) switch (reader.Next)
@ -77,18 +78,22 @@ namespace DOM.DSL.Contexts
text.Append(' '); text.Append(' ');
reader.Move(2); reader.Move(2);
break; break;
case 'r': case 'r':
text.Append(TChar.CaretReturn); text.Append(TChar.CaretReturn);
reader.Move(2); reader.Move(2);
break; break;
case 'n': case 'n':
text.Append(TChar.Newline); text.Append(TChar.Newline);
reader.Move(2); reader.Move(2);
break; break;
case 't': case 't':
text.Append(TChar.Tab); text.Append(TChar.Tab);
reader.Move(2); reader.Move(2);
break; break;
case '@': case '@':
case '(': case '(':
case ')': case ')':
@ -98,6 +103,7 @@ namespace DOM.DSL.Contexts
text.Append(reader.Next); text.Append(reader.Next);
reader.Move(2); reader.Move(2);
break; break;
default: default:
text.Append(reader.Current); text.Append(reader.Current);
reader.Move(); reader.Move();
@ -105,7 +111,8 @@ namespace DOM.DSL.Contexts
} }
} }
break; break;
#endregion
#endregion Ecsaping
case TChar.PropertyIndexEnd: case TChar.PropertyIndexEnd:
{ {
@ -160,6 +167,7 @@ namespace DOM.DSL.Contexts
} }
} }
break; break;
default: default:
{ {
text.Append(reader.Current); text.Append(reader.Current);

@ -40,6 +40,7 @@ namespace DOM.DSL.Contexts
switch (reader.Current) switch (reader.Current)
{ {
#region Ecsaping #region Ecsaping
case TChar.Escape: case TChar.Escape:
{ {
switch (reader.Next) switch (reader.Next)
@ -48,18 +49,22 @@ namespace DOM.DSL.Contexts
text.Append(' '); text.Append(' ');
reader.Move(2); reader.Move(2);
break; break;
case 'r': case 'r':
text.Append(TChar.CaretReturn); text.Append(TChar.CaretReturn);
reader.Move(2); reader.Move(2);
break; break;
case 'n': case 'n':
text.Append(TChar.Newline); text.Append(TChar.Newline);
reader.Move(2); reader.Move(2);
break; break;
case 't': case 't':
text.Append(TChar.Tab); text.Append(TChar.Tab);
reader.Move(2); reader.Move(2);
break; break;
case '@': case '@':
case '(': case '(':
case ')': case ')':
@ -69,6 +74,7 @@ namespace DOM.DSL.Contexts
text.Append(reader.Next); text.Append(reader.Next);
reader.Move(2); reader.Move(2);
break; break;
default: default:
text.Append(reader.Current); text.Append(reader.Current);
reader.Move(); reader.Move();
@ -76,7 +82,8 @@ namespace DOM.DSL.Contexts
} }
} }
break; break;
#endregion
#endregion Ecsaping
case TChar.TokenStart: case TChar.TokenStart:
{ {
@ -122,11 +129,13 @@ namespace DOM.DSL.Contexts
} }
} }
break; break;
case TChar.CaretReturn: case TChar.CaretReturn:
case TChar.Newline: case TChar.Newline:
case TChar.Tab: case TChar.Tab:
reader.Move(); reader.Move();
break; break;
default: default:
{ {
text.Append(reader.Current); text.Append(reader.Current);

@ -9,12 +9,19 @@ namespace DOM.DSL.Contracts
/// Indicates that a table cell body entry is expected. /// Indicates that a table cell body entry is expected.
/// </summary> /// </summary>
bool WaitCellBody { get; } bool WaitCellBody { get; }
void WriteToCell(string part); void WriteToCell(string part);
void EnterTable(Column[] colunmns); void EnterTable(Column[] colunmns);
void EnterRow(int count_columns); void EnterRow(int count_columns);
void EnterCell(int order); void EnterCell(int order);
void LeaveCell(); void LeaveCell();
void LeaveRow(); void LeaveRow();
void FlushTable(StringBuilder builder); void FlushTable(StringBuilder builder);
} }
} }

@ -25,23 +25,94 @@
public int GalleryId { get; private set; } = -1; public int GalleryId { get; private set; } = -1;
public int ImageId { get; private set; } = -1; public int ImageId { get; private set; } = -1;
public void IncSectionId() { SectionId++; } public void IncSectionId()
public void IncParagraphId() { ParagraphId++; } {
public void IncListId() { ListId++; } SectionId++;
public void IncListItemId() { ListItemId++; } }
public void IncTableId() { TableId++; }
public void IncColumnId() { ColumnId++; } public void IncParagraphId()
public void IncRowId() { RowId++; } {
public void IncCellId() { CellId++; } ParagraphId++;
public void IncFormId() { FormId++; } }
public void IncLinkId() { LinkId++; }
public void IncQuoteId() { QuoteId++; } public void IncListId()
public void IncTextId() { TextId++; } {
public void IncAudioplayerId() { AudioplayerId++; } ListId++;
public void IncAudioId() { AudioId++; } }
public void IncVideoplayerId() { VideoplayerId++; }
public void IncVideoId() { VideoId++; } public void IncListItemId()
public void IncGalleryId() { GalleryId++; } {
public void IncImageId() { ImageId++; } ListItemId++;
}
public void IncTableId()
{
TableId++;
}
public void IncColumnId()
{
ColumnId++;
}
public void IncRowId()
{
RowId++;
}
public void IncCellId()
{
CellId++;
}
public void IncFormId()
{
FormId++;
}
public void IncLinkId()
{
LinkId++;
}
public void IncQuoteId()
{
QuoteId++;
}
public void IncTextId()
{
TextId++;
}
public void IncAudioplayerId()
{
AudioplayerId++;
}
public void IncAudioId()
{
AudioId++;
}
public void IncVideoplayerId()
{
VideoplayerId++;
}
public void IncVideoId()
{
VideoId++;
}
public void IncGalleryId()
{
GalleryId++;
}
public void IncImageId()
{
ImageId++;
}
} }
} }

@ -31,6 +31,7 @@ namespace DOM.DSL.Model
TraversElement(item, type, handler); TraversElement(item, type, handler);
} }
break; break;
case ContentElementType.Paragraph: case ContentElementType.Paragraph:
var paragraph = (element as Paragraph); var paragraph = (element as Paragraph);
foreach (var item in paragraph.Parts) foreach (var item in paragraph.Parts)
@ -38,6 +39,7 @@ namespace DOM.DSL.Model
TraversElement(item, type, handler); TraversElement(item, type, handler);
} }
break; break;
case ContentElementType.List: case ContentElementType.List:
var list = (element as List); var list = (element as List);
foreach (var item in list.Items) foreach (var item in list.Items)
@ -45,6 +47,7 @@ namespace DOM.DSL.Model
TraversElement(item, type, handler); TraversElement(item, type, handler);
} }
break; break;
case ContentElementType.Gallery: case ContentElementType.Gallery:
var gallery = (element as Gallery); var gallery = (element as Gallery);
foreach (var item in gallery.Images) foreach (var item in gallery.Images)
@ -52,6 +55,7 @@ namespace DOM.DSL.Model
TraversElement(item, type, handler); TraversElement(item, type, handler);
} }
break; break;
case ContentElementType.Audioplayer: case ContentElementType.Audioplayer:
var audioplayer = (element as Audioplayer); var audioplayer = (element as Audioplayer);
foreach (var item in audioplayer.Tracks) foreach (var item in audioplayer.Tracks)
@ -59,6 +63,7 @@ namespace DOM.DSL.Model
TraversElement(item, type, handler); TraversElement(item, type, handler);
} }
break; break;
case ContentElementType.Videoplayer: case ContentElementType.Videoplayer:
var videoplayer = (element as Videoplayer); var videoplayer = (element as Videoplayer);
foreach (var item in videoplayer.Playlist) foreach (var item in videoplayer.Playlist)
@ -66,6 +71,7 @@ namespace DOM.DSL.Model
TraversElement(item, type, handler); TraversElement(item, type, handler);
} }
break; break;
case ContentElementType.Table: case ContentElementType.Table:
var table = (element as Table); var table = (element as Table);
foreach (var column in table.Columns) foreach (var column in table.Columns)
@ -90,34 +96,49 @@ namespace DOM.DSL.Model
{ {
case "section": case "section":
return ContentElementType.Section; return ContentElementType.Section;
case "paragraph": case "paragraph":
return ContentElementType.Paragraph; return ContentElementType.Paragraph;
case "link": case "link":
return ContentElementType.Link; return ContentElementType.Link;
case "list": case "list":
return ContentElementType.List; return ContentElementType.List;
case "table": case "table":
return ContentElementType.Table; return ContentElementType.Table;
case "audio": case "audio":
return ContentElementType.Audio; return ContentElementType.Audio;
case "audioplayer": case "audioplayer":
return ContentElementType.Audioplayer; return ContentElementType.Audioplayer;
case "form": case "form":
return ContentElementType.Form; return ContentElementType.Form;
case "gallery": case "gallery":
return ContentElementType.Gallery; return ContentElementType.Gallery;
case "image": case "image":
return ContentElementType.Image; return ContentElementType.Image;
case "video": case "video":
return ContentElementType.Video; return ContentElementType.Video;
case "videoplayer": case "videoplayer":
return ContentElementType.Videoplayer; return ContentElementType.Videoplayer;
case "quote": case "quote":
return ContentElementType.Quote; return ContentElementType.Quote;
case "text": case "text":
return ContentElementType.Text; return ContentElementType.Text;
case "column": case "column":
return ContentElementType.Column; return ContentElementType.Column;
case "row": case "row":
return ContentElementType.Row; return ContentElementType.Row;
} }
@ -131,7 +152,7 @@ namespace DOM.DSL.Model
var list = new List<IContentElement>(); var list = new List<IContentElement>();
foreach (var section in _document.Content.Sections) foreach (var section in _document.Content.Sections)
{ {
TraversElement(section, type, e=>list.Add(e)); TraversElement(section, type, e => list.Add(e));
} }
return list; return list;
} }

@ -7,6 +7,7 @@ namespace DOM.DSL.Model
internal sealed class TFlowRules internal sealed class TFlowRules
{ {
#region Rules #region Rules
public TBlockToken ListPrefix; public TBlockToken ListPrefix;
public TBlockToken ListPostfix; public TBlockToken ListPostfix;
public TBlockToken ListItemPrefix; public TBlockToken ListItemPrefix;
@ -55,12 +56,15 @@ namespace DOM.DSL.Model
public TBlockToken VideoplayerPostfix; public TBlockToken VideoplayerPostfix;
public TBlockToken GalleryPrefix; public TBlockToken GalleryPrefix;
public TBlockToken GalleryPostfix; public TBlockToken GalleryPostfix;
#endregion
#endregion Rules
#region Special table builder #region Special table builder
public bool UseSpecialTableBuilder = false; public bool UseSpecialTableBuilder = false;
public ISpecialTableBuilder SpecialTableBuilder; public ISpecialTableBuilder SpecialTableBuilder;
#endregion
#endregion Special table builder
public void Bootstrap() public void Bootstrap()
{ {
@ -124,187 +128,230 @@ namespace DOM.DSL.Model
case "prefix": case "prefix":
ListPrefix = rule_token; ListPrefix = rule_token;
break; break;
case "postfix": case "postfix":
ListPostfix = rule_token; ListPostfix = rule_token;
break; break;
case "ignore": case "ignore":
ListPostfix = ListPrefix = null; ListPostfix = ListPrefix = null;
break; break;
} }
break; break;
case "listitem": case "listitem":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
ListItemPrefix = rule_token; ListItemPrefix = rule_token;
break; break;
case "postfix": case "postfix":
ListItemPostfix = rule_token; ListItemPostfix = rule_token;
break; break;
case "ignore": case "ignore":
ListItemPrefix = ListItemPostfix = null; ListItemPrefix = ListItemPostfix = null;
break; break;
} }
break; break;
case "text": case "text":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
TextPrefix = rule_token; TextPrefix = rule_token;
break; break;
case "template": case "template":
TextTemplate = rule_token; TextTemplate = rule_token;
break; break;
case "postfix": case "postfix":
TextPostfix = rule_token; TextPostfix = rule_token;
break; break;
case "ignore": case "ignore":
TextPrefix = TextTemplate = TextPostfix = null; TextPrefix = TextTemplate = TextPostfix = null;
break; break;
} }
break; break;
case "link": case "link":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
LinkPrefix = rule_token; LinkPrefix = rule_token;
break; break;
case "template": case "template":
LinkTemplate = rule_token; LinkTemplate = rule_token;
break; break;
case "postfix": case "postfix":
LinkPostfix = rule_token; LinkPostfix = rule_token;
break; break;
case "ignore": case "ignore":
LinkPrefix = LinkTemplate = LinkPostfix = null; LinkPrefix = LinkTemplate = LinkPostfix = null;
break; break;
} }
break; break;
case "image": case "image":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
ImagePrefix = rule_token; ImagePrefix = rule_token;
break; break;
case "template": case "template":
ImageTemplate = rule_token; ImageTemplate = rule_token;
break; break;
case "postfix": case "postfix":
ImagePostfix = rule_token; ImagePostfix = rule_token;
break; break;
case "ignore": case "ignore":
ImagePrefix = ImageTemplate = ImagePostfix = null; ImagePrefix = ImageTemplate = ImagePostfix = null;
break; break;
} }
break; break;
case "quote": case "quote":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
QuotePrefix = rule_token; QuotePrefix = rule_token;
break; break;
case "template": case "template":
QuoteTemplate = rule_token; QuoteTemplate = rule_token;
break; break;
case "postfix": case "postfix":
QuotePostfix = rule_token; QuotePostfix = rule_token;
break; break;
case "ignore": case "ignore":
QuotePrefix = QuoteTemplate = QuotePostfix = null; QuotePrefix = QuoteTemplate = QuotePostfix = null;
break; break;
} }
break; break;
case "form": case "form":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
FormPrefix = rule_token; FormPrefix = rule_token;
break; break;
case "template": case "template":
FormTemplate = rule_token; FormTemplate = rule_token;
break; break;
case "postfix": case "postfix":
FormPostfix = rule_token; FormPostfix = rule_token;
break; break;
case "ignore": case "ignore":
FormPrefix = FormTemplate = FormPostfix = null; FormPrefix = FormTemplate = FormPostfix = null;
break; break;
} }
break; break;
case "video": case "video":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
VideoPrefix = rule_token; VideoPrefix = rule_token;
break; break;
case "template": case "template":
VideoTemplate = rule_token; VideoTemplate = rule_token;
break; break;
case "postfix": case "postfix":
VideoPostfix = rule_token; VideoPostfix = rule_token;
break; break;
case "ignore": case "ignore":
VideoPrefix = VideoTemplate = VideoPostfix = null; VideoPrefix = VideoTemplate = VideoPostfix = null;
break; break;
} }
break; break;
case "audio": case "audio":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
AudioPrefix = rule_token; AudioPrefix = rule_token;
break; break;
case "template": case "template":
AudioTemplate = rule_token; AudioTemplate = rule_token;
break; break;
case "postfix": case "postfix":
AudioPostfix = rule_token; AudioPostfix = rule_token;
break; break;
case "ignore": case "ignore":
AudioPrefix = AudioTemplate = AudioPostfix = null; AudioPrefix = AudioTemplate = AudioPostfix = null;
break; break;
} }
break; break;
case "section": case "section":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
SectionPrefix = rule_token; SectionPrefix = rule_token;
break; break;
case "postfix": case "postfix":
SectionPostfix = rule_token; SectionPostfix = rule_token;
break; break;
case "ignore": case "ignore":
SectionPrefix = SectionPostfix = null; SectionPrefix = SectionPostfix = null;
break; break;
} }
break; break;
case "paragraph": case "paragraph":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
ParagraphPrefix = rule_token; ParagraphPrefix = rule_token;
break; break;
case "postfix": case "postfix":
ParagraphPostfix = rule_token; ParagraphPostfix = rule_token;
break; break;
case "ignore": case "ignore":
ParagraphPrefix = ParagraphPostfix = null; ParagraphPrefix = ParagraphPostfix = null;
break; break;
} }
break; break;
case "table": case "table":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
TablePrefix = rule_token; TablePrefix = rule_token;
break; break;
case "postfix": case "postfix":
TablePostfix = rule_token; TablePostfix = rule_token;
break; break;
case "ignore": case "ignore":
TablePrefix = TablePostfix = null; TablePrefix = TablePostfix = null;
break; break;
case "special": // Using a hardcoded table conversion case "special": // Using a hardcoded table conversion
//TablePrefix = TablePostfix = null; //TablePrefix = TablePostfix = null;
ColumnsPrefix = ColumnsPostfix = null; ColumnsPrefix = ColumnsPostfix = null;
@ -318,103 +365,124 @@ namespace DOM.DSL.Model
break; break;
} }
break; break;
case "columns": case "columns":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
ColumnsPrefix = rule_token; ColumnsPrefix = rule_token;
break; break;
case "postfix": case "postfix":
ColumnsPostfix = rule_token; ColumnsPostfix = rule_token;
break; break;
case "ignore": case "ignore":
ColumnsPrefix = ColumnsPostfix = null; ColumnsPrefix = ColumnsPostfix = null;
break; break;
} }
break; break;
case "column": case "column":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
ColumnPrefix = rule_token; ColumnPrefix = rule_token;
break; break;
case "template": case "template":
ColumnTemplate = rule_token; ColumnTemplate = rule_token;
break; break;
case "postfix": case "postfix":
ColumnPostfix = rule_token; ColumnPostfix = rule_token;
break; break;
case "ignore": case "ignore":
ColumnPrefix = ColumnTemplate = ColumnPostfix = null; ColumnPrefix = ColumnTemplate = ColumnPostfix = null;
break; break;
} }
break; break;
case "tablerow": case "tablerow":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
RowPrefix = rule_token; RowPrefix = rule_token;
break; break;
case "postfix": case "postfix":
RowPostfix = rule_token; RowPostfix = rule_token;
break; break;
case "ignore": case "ignore":
RowPrefix = RowPostfix = null; RowPrefix = RowPostfix = null;
break; break;
} }
break; break;
case "tablecell": case "tablecell":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
CellPrefix = rule_token; CellPrefix = rule_token;
break; break;
case "postfix": case "postfix":
CellPostfix = rule_token; CellPostfix = rule_token;
break; break;
case "ignore": case "ignore":
CellPrefix = CellPostfix = null; CellPrefix = CellPostfix = null;
break; break;
} }
break; break;
case "videoplayer": case "videoplayer":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
VideoplayerPrefix = rule_token; VideoplayerPrefix = rule_token;
break; break;
case "postfix": case "postfix":
VideoplayerPostfix = rule_token; VideoplayerPostfix = rule_token;
break; break;
case "ignore": case "ignore":
VideoplayerPrefix = VideoplayerPostfix = null; VideoplayerPrefix = VideoplayerPostfix = null;
break; break;
} }
break; break;
case "audioplayer": case "audioplayer":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
AudioplayerPrefix = rule_token; AudioplayerPrefix = rule_token;
break; break;
case "postfix": case "postfix":
AudioplayerPostfix = rule_token; AudioplayerPostfix = rule_token;
break; break;
case "ignore": case "ignore":
AudioplayerPrefix = AudioplayerPostfix = null; AudioplayerPrefix = AudioplayerPostfix = null;
break; break;
} }
break; break;
case "gallery": case "gallery":
switch (functionName) switch (functionName)
{ {
case "prefix": case "prefix":
GalleryPrefix = rule_token; GalleryPrefix = rule_token;
break; break;
case "postfix": case "postfix":
GalleryPostfix = rule_token; GalleryPostfix = rule_token;
break; break;
case "ignore": case "ignore":
GalleryPrefix = GalleryPostfix = null; GalleryPrefix = GalleryPostfix = null;
break; break;

@ -38,7 +38,7 @@ namespace DOM.DSL.Model
.Select(i => word.Substring(i * max, max)). .Select(i => word.Substring(i * max, max)).
ToArray(); ToArray();
int k = 0; int k = 0;
if(current_max > 0) text.Append("\r\n"); if (current_max > 0) text.Append("\r\n");
for (; k < lines.Length - 1; k++) for (; k < lines.Length - 1; k++)
{ {
text.Append(lines[k]); text.Append(lines[k]);

@ -31,6 +31,7 @@ namespace DOM.DSL.Services
public int RowCellIndex = -1; public int RowCellIndex = -1;
private StringBuilder _cellBody = new StringBuilder(); private StringBuilder _cellBody = new StringBuilder();
public void FlushCell() public void FlushCell()
{ {
if (RowCellIndex >= 0) if (RowCellIndex >= 0)
@ -51,6 +52,7 @@ namespace DOM.DSL.Services
return TextTableRender.Render(Data, options); return TextTableRender.Render(Data, options);
} }
} }
private readonly TextTableRenderOptions _options; private readonly TextTableRenderOptions _options;
private Stack<TextTableMeta> _textTables = new Stack<TextTableMeta>(); private Stack<TextTableMeta> _textTables = new Stack<TextTableMeta>();

File diff suppressed because it is too large Load Diff

@ -22,6 +22,7 @@ namespace DOM.DSL.Services
c.Reset(value); c.Reset(value);
return c; return c;
} }
internal TContainer Get(object value, int index) internal TContainer Get(object value, int index)
{ {
Interlocked.Increment(ref _get_count); Interlocked.Increment(ref _get_count);
@ -30,6 +31,7 @@ namespace DOM.DSL.Services
c.Index = index; c.Index = index;
return c; return c;
} }
internal void Release(TContainer container) internal void Release(TContainer container)
{ {
if (container != null) if (container != null)
@ -40,6 +42,7 @@ namespace DOM.DSL.Services
} }
public static int GetsCount() => _get_count; public static int GetsCount() => _get_count;
public static int ReleasesCount() => _release_count; public static int ReleasesCount() => _release_count;
} }
} }

@ -54,6 +54,7 @@ namespace DOM.DSL.Services
} }
#region Primitives #region Primitives
public void ReadAudio(Audio audio, int order) public void ReadAudio(Audio audio, int order)
{ {
_render.Counter.IncAudioId(); _render.Counter.IncAudioId();
@ -189,9 +190,11 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.VideoPostfix, video, order)); WriteText(Resolve(_transformRules.VideoPostfix, video, order));
} }
} }
#endregion
#endregion Primitives
#region Containers #region Containers
public void EnterParagraph(Paragraph paragraph) public void EnterParagraph(Paragraph paragraph)
{ {
_render.Counter.IncParagraphId(); _render.Counter.IncParagraphId();
@ -200,6 +203,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.ParagraphPrefix, paragraph, _render.Counter.ParagraphId)); WriteText(Resolve(_transformRules.ParagraphPrefix, paragraph, _render.Counter.ParagraphId));
} }
} }
public void LeaveParagraph(Paragraph paragraph) public void LeaveParagraph(Paragraph paragraph)
{ {
if (_transformRules.ParagraphPostfix != null) if (_transformRules.ParagraphPostfix != null)
@ -207,6 +211,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.ParagraphPostfix, paragraph, _render.Counter.ParagraphId)); WriteText(Resolve(_transformRules.ParagraphPostfix, paragraph, _render.Counter.ParagraphId));
} }
} }
public void EnterSection(Section section) public void EnterSection(Section section)
{ {
_render.Counter.IncSectionId(); _render.Counter.IncSectionId();
@ -215,6 +220,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.SectionPrefix, section, _render.Counter.SectionId)); WriteText(Resolve(_transformRules.SectionPrefix, section, _render.Counter.SectionId));
} }
} }
public void LeaveSection(Section section) public void LeaveSection(Section section)
{ {
if (_transformRules.SectionPostfix != null) if (_transformRules.SectionPostfix != null)
@ -222,9 +228,11 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.SectionPostfix, section, _render.Counter.SectionId)); WriteText(Resolve(_transformRules.SectionPostfix, section, _render.Counter.SectionId));
} }
} }
#endregion
#endregion Containers
#region Table #region Table
public void EnterTable(Table table) public void EnterTable(Table table)
{ {
_render.Counter.IncTableId(); _render.Counter.IncTableId();
@ -238,6 +246,7 @@ namespace DOM.DSL.Services
_specialTableBuilder.EnterTable(table.Columns.ToArray()); _specialTableBuilder.EnterTable(table.Columns.ToArray());
} }
} }
public void EnterColumns(Table table) public void EnterColumns(Table table)
{ {
if (_useSpecialTableBuilder == false && _transformRules.ColumnsPrefix != null) if (_useSpecialTableBuilder == false && _transformRules.ColumnsPrefix != null)
@ -245,6 +254,7 @@ namespace DOM.DSL.Services
_builder.Append(Resolve(_transformRules.ColumnsPrefix, table.Columns, 0)); _builder.Append(Resolve(_transformRules.ColumnsPrefix, table.Columns, 0));
} }
} }
public void EnterRow(Table table, Row row, int order) public void EnterRow(Table table, Row row, int order)
{ {
_render.Counter.IncRowId(); _render.Counter.IncRowId();
@ -257,6 +267,7 @@ namespace DOM.DSL.Services
_builder.Append(Resolve(_transformRules.RowPrefix, row, order)); _builder.Append(Resolve(_transformRules.RowPrefix, row, order));
} }
} }
public void EnterRowCell(Table table, Row row, IContentElement cell, int order) public void EnterRowCell(Table table, Row row, IContentElement cell, int order)
{ {
_render.Counter.IncCellId(); _render.Counter.IncCellId();
@ -276,6 +287,7 @@ namespace DOM.DSL.Services
} }
} }
} }
public void LeaveColumns(Table table) public void LeaveColumns(Table table)
{ {
if (_useSpecialTableBuilder == false && _transformRules.ColumnsPostfix != null) if (_useSpecialTableBuilder == false && _transformRules.ColumnsPostfix != null)
@ -283,6 +295,7 @@ namespace DOM.DSL.Services
_builder.Append(Resolve(_transformRules.ColumnsPostfix, table.Columns, 0)); _builder.Append(Resolve(_transformRules.ColumnsPostfix, table.Columns, 0));
} }
} }
public void LeaveRow(Table table, Row row, int order) public void LeaveRow(Table table, Row row, int order)
{ {
if (_useSpecialTableBuilder) if (_useSpecialTableBuilder)
@ -294,6 +307,7 @@ namespace DOM.DSL.Services
_builder.Append(Resolve(_transformRules.RowPostfix, row, order)); _builder.Append(Resolve(_transformRules.RowPostfix, row, order));
} }
} }
public void LeaveRowCell(Table table, Row row, IContentElement cell, int order) public void LeaveRowCell(Table table, Row row, IContentElement cell, int order)
{ {
if (_useSpecialTableBuilder) if (_useSpecialTableBuilder)
@ -312,6 +326,7 @@ namespace DOM.DSL.Services
} }
} }
} }
public void LeaveTable(Table table) public void LeaveTable(Table table)
{ {
if (_useSpecialTableBuilder) if (_useSpecialTableBuilder)
@ -323,9 +338,11 @@ namespace DOM.DSL.Services
_builder.Append(Resolve(_transformRules.TablePostfix, table, _render.Counter.TableId)); _builder.Append(Resolve(_transformRules.TablePostfix, table, _render.Counter.TableId));
} }
} }
#endregion
#endregion Table
#region List #region List
public void EnterList(List list) public void EnterList(List list)
{ {
_render.Counter.IncListId(); _render.Counter.IncListId();
@ -334,6 +351,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.ListPrefix, list, 0)); WriteText(Resolve(_transformRules.ListPrefix, list, 0));
} }
} }
public void EnterListItem(List list, IContentElement item, int order) public void EnterListItem(List list, IContentElement item, int order)
{ {
_render.Counter.IncListItemId(); _render.Counter.IncListItemId();
@ -342,6 +360,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.ListItemPrefix, item, order)); WriteText(Resolve(_transformRules.ListItemPrefix, item, order));
} }
} }
public void LeaveList(List list) public void LeaveList(List list)
{ {
if (_transformRules.ListPostfix != null) if (_transformRules.ListPostfix != null)
@ -349,6 +368,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.ListPostfix, list, 0)); WriteText(Resolve(_transformRules.ListPostfix, list, 0));
} }
} }
public void LeaveListItem(List list, IContentElement item, int order) public void LeaveListItem(List list, IContentElement item, int order)
{ {
if (_transformRules.ListItemPostfix != null) if (_transformRules.ListItemPostfix != null)
@ -356,9 +376,11 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.ListItemPostfix, item, order)); WriteText(Resolve(_transformRules.ListItemPostfix, item, order));
} }
} }
#endregion
#endregion List
#region Media #region Media
public void EnterAudioplayer(Audioplayer player) public void EnterAudioplayer(Audioplayer player)
{ {
_render.Counter.IncAudioplayerId(); _render.Counter.IncAudioplayerId();
@ -367,6 +389,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.AudioplayerPrefix, player, 0)); WriteText(Resolve(_transformRules.AudioplayerPrefix, player, 0));
} }
} }
public void EnterGallery(Gallery gallery) public void EnterGallery(Gallery gallery)
{ {
_render.Counter.IncGalleryId(); _render.Counter.IncGalleryId();
@ -375,6 +398,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.GalleryPrefix, gallery, 0)); WriteText(Resolve(_transformRules.GalleryPrefix, gallery, 0));
} }
} }
public void EnterVideoplayer(Videoplayer player) public void EnterVideoplayer(Videoplayer player)
{ {
_render.Counter.IncVideoplayerId(); _render.Counter.IncVideoplayerId();
@ -383,6 +407,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.VideoplayerPrefix, player, 0)); WriteText(Resolve(_transformRules.VideoplayerPrefix, player, 0));
} }
} }
public void LeaveAudioplayer(Audioplayer player) public void LeaveAudioplayer(Audioplayer player)
{ {
if (_transformRules.AudioplayerPostfix != null) if (_transformRules.AudioplayerPostfix != null)
@ -390,6 +415,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.AudioplayerPostfix, player, 0)); WriteText(Resolve(_transformRules.AudioplayerPostfix, player, 0));
} }
} }
public void LeaveGallery(Gallery gallery) public void LeaveGallery(Gallery gallery)
{ {
if (_transformRules.GalleryPostfix != null) if (_transformRules.GalleryPostfix != null)
@ -397,6 +423,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.GalleryPostfix, gallery, 0)); WriteText(Resolve(_transformRules.GalleryPostfix, gallery, 0));
} }
} }
public void LeaveVideoplayer(Videoplayer player) public void LeaveVideoplayer(Videoplayer player)
{ {
if (_transformRules.VideoplayerPostfix != null) if (_transformRules.VideoplayerPostfix != null)
@ -404,6 +431,7 @@ namespace DOM.DSL.Services
WriteText(Resolve(_transformRules.VideoplayerPostfix, player, 0)); WriteText(Resolve(_transformRules.VideoplayerPostfix, player, 0));
} }
} }
#endregion
#endregion Media
} }
} }

@ -238,6 +238,7 @@ namespace DOM.DSL.Services
} }
} }
break; break;
case "flow": case "flow":
{ {
return new List<TContainer> return new List<TContainer>
@ -356,6 +357,7 @@ namespace DOM.DSL.Services
Log.Debug(args[0].ToString(), args.Skip(1).ToArray()); Log.Debug(args[0].ToString(), args.Skip(1).ToArray());
} }
break; break;
case "validate": case "validate":
if (args?.Length == 1) if (args?.Length == 1)
{ {
@ -364,15 +366,18 @@ namespace DOM.DSL.Services
case "xml": case "xml":
Options.ValidateAsXml = true; Options.ValidateAsXml = true;
break; break;
case "html": case "html":
Options.ValidateAsHtml = true; Options.ValidateAsHtml = true;
break; break;
case "json": case "json":
Options.ValidateAsJson = true; Options.ValidateAsJson = true;
break; break;
} }
} }
break; break;
case "fixwidth": case "fixwidth":
{ {
if (args?.Length == 1) if (args?.Length == 1)

@ -10,6 +10,7 @@
/// Имя элемента /// Имя элемента
/// </summary> /// </summary>
public string ElementName; public string ElementName;
/// <summary> /// <summary>
/// Optionally, next token /// Optionally, next token
/// </summary> /// </summary>

@ -8,16 +8,23 @@ namespace DOM.DSL.Tokens
public abstract class TToken : TCloneable public abstract class TToken : TCloneable
{ {
public abstract TToken Clone(); public abstract TToken Clone();
/// <summary> /// <summary>
/// Copying token with set NextToken to null, to break cycle /// Copying token with set NextToken to null, to break cycle
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public abstract TToken CloneLocal(); public abstract TToken CloneLocal();
public TElementToken AsElementToken() => this as TElementToken; public TElementToken AsElementToken() => this as TElementToken;
public TFunctionToken AsFunctionToken() => this as TFunctionToken; public TFunctionToken AsFunctionToken() => this as TFunctionToken;
public TTextToken AsTextToken() => this as TTextToken; public TTextToken AsTextToken() => this as TTextToken;
public TBlockToken AsBlockToken() => this as TBlockToken; public TBlockToken AsBlockToken() => this as TBlockToken;
public TPropertyToken AsPropertyToken() => this as TPropertyToken; public TPropertyToken AsPropertyToken() => this as TPropertyToken;
public TSystemToken AsSystemToken() => this as TSystemToken; public TSystemToken AsSystemToken() => this as TSystemToken;
} }
} }

@ -8,22 +8,43 @@ namespace ZeroLevel.DocumentObjectModel
/// Agency name /// Agency name
/// </summary> /// </summary>
public string Title; public string Title;
/// <summary> /// <summary>
/// Agency website /// Agency website
/// </summary> /// </summary>
public string Url; public string Url;
/// <summary> /// <summary>
/// Description /// Description
/// </summary> /// </summary>
public string Description; public string Description;
public Agency() { } public Agency()
public Agency(IBinaryReader reader) { Deserialize(reader); } {
public Agency(string title) { this.Title = title; } }
public Agency(string title, string url) { this.Title = title; this.Url = url; }
public Agency(string title, string url, string description) { this.Title = title; this.Url = url; this.Description = description; } public Agency(IBinaryReader reader)
{
Deserialize(reader);
}
public Agency(string title)
{
this.Title = title;
}
public Agency(string title, string url)
{
this.Title = title; this.Url = url;
}
public Agency(string title, string url, string description)
{
this.Title = title; this.Url = url; this.Description = description;
}
#region IBinarySerializable #region IBinarySerializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteString(this.Title); writer.WriteString(this.Title);
@ -37,6 +58,7 @@ namespace ZeroLevel.DocumentObjectModel
this.Url = reader.ReadString(); this.Url = reader.ReadString();
this.Description = reader.ReadString(); this.Description = reader.ReadString();
} }
#endregion
#endregion IBinarySerializable
} }
} }

@ -7,25 +7,31 @@ namespace ZeroLevel.DocumentObjectModel
IBinarySerializable IBinarySerializable
{ {
#region Fields #region Fields
/// <summary> /// <summary>
/// Title /// Title
/// </summary> /// </summary>
public string Title; public string Title;
/// <summary> /// <summary>
/// Description /// Description
/// </summary> /// </summary>
public string Description; public string Description;
/// <summary> /// <summary>
/// Binded document reference /// Binded document reference
/// </summary> /// </summary>
public Guid DocumentId; public Guid DocumentId;
/// <summary> /// <summary>
/// Relation type /// Relation type
/// </summary> /// </summary>
public AssotiationRelation Relation; public AssotiationRelation Relation;
#endregion
#endregion Fields
#region IBinarySerializable #region IBinarySerializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteString(this.Title); writer.WriteString(this.Title);
@ -41,6 +47,7 @@ namespace ZeroLevel.DocumentObjectModel
this.DocumentId = reader.ReadGuid(); this.DocumentId = reader.ReadGuid();
this.Relation = (AssotiationRelation)reader.ReadInt32(); this.Relation = (AssotiationRelation)reader.ReadInt32();
} }
#endregion
#endregion IBinarySerializable
} }
} }

@ -8,18 +8,22 @@ namespace ZeroLevel.DocumentObjectModel
/// Relation type not defined /// Relation type not defined
/// </summary> /// </summary>
Uncknown = 0, Uncknown = 0,
/// <summary> /// <summary>
/// Mentioned /// Mentioned
/// </summary> /// </summary>
Mentions = 1, Mentions = 1,
/// <summary> /// <summary>
/// It tells about /// It tells about
/// </summary> /// </summary>
About = 2, About = 2,
/// <summary> /// <summary>
/// Previous version update /// Previous version update
/// </summary> /// </summary>
UpdateOf = 3, UpdateOf = 3,
/// <summary> /// <summary>
/// Based on /// Based on
/// </summary> /// </summary>

@ -10,29 +10,41 @@ namespace ZeroLevel.DocumentObjectModel
/// ID /// ID
/// </summary> /// </summary>
public string Identity; public string Identity;
/// <summary> /// <summary>
/// Title /// Title
/// </summary> /// </summary>
public string Caption; public string Caption;
/// <summary> /// <summary>
/// Description (optional) /// Description (optional)
/// </summary> /// </summary>
public string Summary; public string Summary;
/// <summary> /// <summary>
/// Content type /// Content type
/// </summary> /// </summary>
public ContentType ContentType; public ContentType ContentType;
/// <summary> /// <summary>
/// Binary content /// Binary content
/// </summary> /// </summary>
public byte[] Payload; public byte[] Payload;
public AttachContent() { } public AttachContent()
public AttachContent(IBinaryReader reader) { Deserialize(reader); } {
}
public AttachContent(IBinaryReader reader)
{
Deserialize(reader);
}
public AttachContent(string identity, string caption, string description) public AttachContent(string identity, string caption, string description)
{ Identity = identity; Summary = description; Caption = caption; } { Identity = identity; Summary = description; Caption = caption; }
#region IBinarySerializable #region IBinarySerializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteString(this.Identity); writer.WriteString(this.Identity);
@ -50,6 +62,7 @@ namespace ZeroLevel.DocumentObjectModel
this.ContentType = (ContentType)reader.ReadInt32(); this.ContentType = (ContentType)reader.ReadInt32();
this.Payload = reader.ReadBytes(); this.Payload = reader.ReadBytes();
} }
#endregion
#endregion IBinarySerializable
} }
} }

@ -38,7 +38,7 @@ namespace ZeroLevel.DocumentObjectModel
Deserialize(reader); Deserialize(reader);
} }
#endregion #endregion Ctors
#region Fields #region Fields
@ -67,7 +67,7 @@ namespace ZeroLevel.DocumentObjectModel
/// </summary> /// </summary>
public bool IsSystem { get; set; } public bool IsSystem { get; set; }
#endregion #endregion Fields
#region IBinarySerializable #region IBinarySerializable
@ -89,7 +89,7 @@ namespace ZeroLevel.DocumentObjectModel
this.IsSystem = reader.ReadBoolean(); this.IsSystem = reader.ReadBoolean();
} }
#endregion #endregion IBinarySerializable
#region ICloneable #region ICloneable
@ -98,7 +98,7 @@ namespace ZeroLevel.DocumentObjectModel
return new Category(this); return new Category(this);
} }
#endregion #endregion ICloneable
#region IEquatable #region IEquatable
@ -113,7 +113,7 @@ namespace ZeroLevel.DocumentObjectModel
return true; return true;
} }
#endregion #endregion IEquatable
#region Equals & Hash #region Equals & Hash
@ -131,6 +131,6 @@ namespace ZeroLevel.DocumentObjectModel
IsSystem.GetHashCode(); IsSystem.GetHashCode();
} }
#endregion #endregion Equals & Hash
} }
} }

@ -2,7 +2,7 @@
namespace ZeroLevel.DocumentObjectModel namespace ZeroLevel.DocumentObjectModel
{ {
public enum ContentType: Int32 public enum ContentType : Int32
{ {
Raw = 0, Raw = 0,
Text = 1, Text = 1,

@ -7,8 +7,15 @@ namespace ZeroLevel.DocumentObjectModel
public sealed class DescriptiveMetadata : public sealed class DescriptiveMetadata :
IBinarySerializable IBinarySerializable
{ {
public DescriptiveMetadata() { Initialize(); } public DescriptiveMetadata()
public DescriptiveMetadata(IBinaryReader reader) { Deserialize(reader); } {
Initialize();
}
public DescriptiveMetadata(IBinaryReader reader)
{
Deserialize(reader);
}
private void Initialize() private void Initialize()
{ {
@ -22,45 +29,56 @@ namespace ZeroLevel.DocumentObjectModel
} }
#region Fields #region Fields
/// <summary> /// <summary>
/// Authors /// Authors
/// </summary> /// </summary>
public string Byline; public string Byline;
/// <summary> /// <summary>
/// Copyright /// Copyright
/// </summary> /// </summary>
public string CopyrightNotice; public string CopyrightNotice;
/// <summary> /// <summary>
/// Creation date /// Creation date
/// </summary> /// </summary>
public DateTime Created; public DateTime Created;
/// <summary> /// <summary>
/// Main language /// Main language
/// </summary> /// </summary>
public string Language; public string Language;
/// <summary> /// <summary>
/// Priority /// Priority
/// </summary> /// </summary>
public Priority Priority; public Priority Priority;
/// <summary> /// <summary>
/// Document source /// Document source
/// </summary> /// </summary>
public Agency Source; public Agency Source;
/// <summary> /// <summary>
/// Document publisher /// Document publisher
/// </summary> /// </summary>
public Agency Publisher; public Agency Publisher;
/// <summary> /// <summary>
/// Reference to original document /// Reference to original document
/// </summary> /// </summary>
public Tag Original; public Tag Original;
/// <summary> /// <summary>
/// Headers (optional) /// Headers (optional)
/// </summary> /// </summary>
public List<Header> Headers; public List<Header> Headers;
#endregion
#endregion Fields
#region IBinarySerializable #region IBinarySerializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteString(this.Byline); writer.WriteString(this.Byline);
@ -89,6 +107,7 @@ namespace ZeroLevel.DocumentObjectModel
this.Source = new Agency(); this.Source = new Agency();
this.Source.Deserialize(reader); this.Source.Deserialize(reader);
} }
#endregion
#endregion IBinarySerializable
} }
} }

@ -8,6 +8,7 @@ namespace ZeroLevel.DocumentObjectModel
: IBinarySerializable : IBinarySerializable
{ {
private static readonly Document _empty = new Document(); private static readonly Document _empty = new Document();
public static Document Empty public static Document Empty
{ {
get get
@ -17,9 +18,21 @@ namespace ZeroLevel.DocumentObjectModel
} }
} }
public Document() { Id = Guid.NewGuid(); Initialize(); } public Document()
public Document(Guid id) { Id = id; Initialize(); } {
public Document(IBinaryReader reader) { Deserialize(reader); } Id = Guid.NewGuid(); Initialize();
}
public Document(Guid id)
{
Id = id; Initialize();
}
public Document(IBinaryReader reader)
{
Deserialize(reader);
}
public Document(Document other) public Document(Document other)
{ {
var data = MessageSerializer.Serialize(other); var data = MessageSerializer.Serialize(other);
@ -44,45 +57,54 @@ namespace ZeroLevel.DocumentObjectModel
/// ID /// ID
/// </summary> /// </summary>
public Guid Id; public Guid Id;
/// <summary> /// <summary>
/// Short description /// Short description
/// </summary> /// </summary>
public string Summary; public string Summary;
/// <summary> /// <summary>
/// Title /// Title
/// </summary> /// </summary>
public string Header; public string Header;
/// <summary> /// <summary>
/// Identification block /// Identification block
/// </summary> /// </summary>
public Identifier Identifier; public Identifier Identifier;
/// <summary> /// <summary>
/// Content /// Content
/// </summary> /// </summary>
public FlowContent Content; public FlowContent Content;
/// <summary> /// <summary>
/// Tags /// Tags
/// </summary> /// </summary>
public TagMetadata TagMetadata; public TagMetadata TagMetadata;
/// <summary> /// <summary>
/// Metadata /// Metadata
/// </summary> /// </summary>
public DescriptiveMetadata DescriptiveMetadata; public DescriptiveMetadata DescriptiveMetadata;
/// <summary> /// <summary>
/// Attachments /// Attachments
/// </summary> /// </summary>
public List<AttachContent> Attachments; public List<AttachContent> Attachments;
/// <summary> /// <summary>
/// Binded documents /// Binded documents
/// </summary> /// </summary>
public List<Assotiation> Assotiations; public List<Assotiation> Assotiations;
/// <summary> /// <summary>
/// Categories /// Categories
/// </summary> /// </summary>
public List<Category> Categories; public List<Category> Categories;
#region IBinarySerializable #region IBinarySerializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteGuid(this.Id); writer.WriteGuid(this.Id);
@ -114,6 +136,7 @@ namespace ZeroLevel.DocumentObjectModel
this.Assotiations = reader.ReadCollection<Assotiation>(); this.Assotiations = reader.ReadCollection<Assotiation>();
this.Categories = reader.ReadCollection<Category>(); this.Categories = reader.ReadCollection<Category>();
} }
#endregion
#endregion IBinarySerializable
} }
} }

@ -7,10 +7,12 @@ namespace ZeroLevel.DocumentObjectModel.Flow
ContentElement ContentElement
{ {
public SourceType Source { get; set; } public SourceType Source { get; set; }
/// <summary> /// <summary>
/// Title /// Title
/// </summary> /// </summary>
public string Title; public string Title;
/// <summary> /// <summary>
/// Link or Attachment ID /// Link or Attachment ID
/// </summary> /// </summary>

@ -15,6 +15,7 @@ namespace ZeroLevel.DocumentObjectModel.Flow
{ {
this.Caption = caption; this.Caption = caption;
} }
public Column(IBinaryReader reader) : base(ContentElementType.Column) public Column(IBinaryReader reader) : base(ContentElementType.Column)
{ {
Deserialize(reader); Deserialize(reader);

@ -6,6 +6,7 @@ namespace ZeroLevel.DocumentObjectModel.Flow
IContentElement IContentElement
{ {
protected ContentElementType _type; protected ContentElementType _type;
public ContentElementType Type public ContentElementType Type
{ {
get get
@ -20,6 +21,7 @@ namespace ZeroLevel.DocumentObjectModel.Flow
} }
public abstract void Serialize(IBinaryWriter writer); public abstract void Serialize(IBinaryWriter writer);
public abstract void Deserialize(IBinaryReader reader); public abstract void Deserialize(IBinaryReader reader);
} }
} }

@ -6,13 +6,16 @@ namespace ZeroLevel.DocumentObjectModel.Flow
{ {
// Primitives // Primitives
Text = 0, Text = 0,
Quote = 1, Quote = 1,
Link = 2, Link = 2,
Image = 3, Image = 3,
Audio = 4, Audio = 4,
Video = 5, Video = 5,
// Containers // Containers
Section = 100, Section = 100,
Paragraph = 101, Paragraph = 101,
List = 102, List = 102,
Table = 103, Table = 103,
@ -21,8 +24,10 @@ namespace ZeroLevel.DocumentObjectModel.Flow
Videoplayer = 106, Videoplayer = 106,
Row = 107, Row = 107,
Column = 108, Column = 108,
// Feature // Feature
Form = 200, Form = 200,
Content = 500, Content = 500,
Unknown = 1000 Unknown = 1000
} }

@ -11,14 +11,17 @@ namespace ZeroLevel.DocumentObjectModel.Flow
/// None /// None
/// </summary> /// </summary>
None = 0, None = 0,
/// <summary> /// <summary>
/// Flow: left /// Flow: left
/// </summary> /// </summary>
Left = 1, Left = 1,
/// <summary> /// <summary>
/// Flow: right /// Flow: right
/// </summary> /// </summary>
Right = 2, Right = 2,
/// <summary> /// <summary>
/// Block /// Block
/// </summary> /// </summary>

@ -8,16 +8,17 @@ namespace ZeroLevel.DocumentObjectModel.Flow
{ {
public SourceType Source { get; set; } public SourceType Source { get; set; }
public FlowAlign Align = FlowAlign.None; public FlowAlign Align = FlowAlign.None;
/// <summary> /// <summary>
/// Title /// Title
/// </summary> /// </summary>
public string Title; public string Title;
/// <summary> /// <summary>
/// Link or Attachment ID /// Link or Attachment ID
/// </summary> /// </summary>
public string Identifier; public string Identifier;
public Image() : base(ContentElementType.Image) public Image() : base(ContentElementType.Image)
{ {
} }

@ -35,6 +35,7 @@ namespace ZeroLevel.DocumentObjectModel.Flow
} }
#region Serialization #region Serialization
public override void Serialize(IBinaryWriter writer) public override void Serialize(IBinaryWriter writer)
{ {
ContentElementSerializer.WriteCollection(writer, this.Parts); ContentElementSerializer.WriteCollection(writer, this.Parts);
@ -44,6 +45,7 @@ namespace ZeroLevel.DocumentObjectModel.Flow
{ {
this.Parts = ContentElementSerializer.ReadCollection(reader); this.Parts = ContentElementSerializer.ReadCollection(reader);
} }
#endregion
#endregion Serialization
} }
} }

@ -35,6 +35,7 @@ namespace ZeroLevel.DocumentObjectModel.Flow
} }
#region Serialization #region Serialization
public override void Serialize(IBinaryWriter writer) public override void Serialize(IBinaryWriter writer)
{ {
ContentElementSerializer.WriteCollection(writer, this.Parts); ContentElementSerializer.WriteCollection(writer, this.Parts);
@ -44,6 +45,7 @@ namespace ZeroLevel.DocumentObjectModel.Flow
{ {
this.Parts = ContentElementSerializer.ReadCollection(reader); this.Parts = ContentElementSerializer.ReadCollection(reader);
} }
#endregion
#endregion Serialization
} }
} }

@ -11,11 +11,13 @@ namespace ZeroLevel.DocumentObjectModel.Flow
public Text() : base(ContentElementType.Text) public Text() : base(ContentElementType.Text)
{ {
} }
public Text(string value) : public Text(string value) :
base(ContentElementType.Text) base(ContentElementType.Text)
{ {
this.Value = value; this.Value = value;
} }
public Text(IBinaryReader reader) : public Text(IBinaryReader reader) :
base(ContentElementType.Text) base(ContentElementType.Text)
{ {

@ -7,10 +7,12 @@ namespace ZeroLevel.DocumentObjectModel.Flow
ContentElement ContentElement
{ {
public SourceType Source { get; set; } public SourceType Source { get; set; }
/// <summary> /// <summary>
/// Title /// Title
/// </summary> /// </summary>
public string Title; public string Title;
/// <summary> /// <summary>
/// Link or Attachment ID /// Link or Attachment ID
/// </summary> /// </summary>
@ -19,6 +21,7 @@ namespace ZeroLevel.DocumentObjectModel.Flow
public Video() : base(ContentElementType.Video) public Video() : base(ContentElementType.Video)
{ {
} }
public Video(IBinaryReader reader) : public Video(IBinaryReader reader) :
base(ContentElementType.Video) base(ContentElementType.Video)
{ {

@ -13,6 +13,7 @@ namespace ZeroLevel.DocumentObjectModel.Flow
base(ContentElementType.Videoplayer) base(ContentElementType.Videoplayer)
{ {
} }
public Videoplayer(IBinaryReader reader) : public Videoplayer(IBinaryReader reader) :
base(ContentElementType.Videoplayer) base(ContentElementType.Videoplayer)
{ {

@ -10,7 +10,8 @@ namespace ZeroLevel.DocumentObjectModel
public List<Section> Sections = new List<Section>(); public List<Section> Sections = new List<Section>();
public FlowContent() : public FlowContent() :
base(ContentElementType.Content) { } base(ContentElementType.Content)
{ }
public FlowContent(IBinaryReader reader) : public FlowContent(IBinaryReader reader) :
base(ContentElementType.Content) base(ContentElementType.Content)

@ -9,11 +9,31 @@ namespace ZeroLevel.DocumentObjectModel
ICloneable ICloneable
{ {
#region Ctors #region Ctors
public Header() { }
public Header(string name) { this.Name = name; } public Header()
public Header(string name, string value) { this.Name = name; this.Value = value; } {
public Header(string name, string value, string type) { this.Name = name; this.Value = value; this.Type = type; } }
public Header(string name, string value, string type, string tag) { this.Name = name; this.Value = value; this.Type = type; this.Tag = tag; }
public Header(string name)
{
this.Name = name;
}
public Header(string name, string value)
{
this.Name = name; this.Value = value;
}
public Header(string name, string value, string type)
{
this.Name = name; this.Value = value; this.Type = type;
}
public Header(string name, string value, string type, string tag)
{
this.Name = name; this.Value = value; this.Type = type; this.Tag = tag;
}
public Header(Header other) public Header(Header other)
{ {
this.Name = other.Name; this.Name = other.Name;
@ -21,16 +41,20 @@ namespace ZeroLevel.DocumentObjectModel
this.Type = other.Type; this.Type = other.Type;
this.Value = other.Value; this.Value = other.Value;
} }
#endregion
#endregion Ctors
#region Fields #region Fields
public string Name; public string Name;
public string Value; public string Value;
public string Type; public string Type;
public string Tag; public string Tag;
#endregion
#endregion Fields
#region IBinarySerializable #region IBinarySerializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteString(Name); writer.WriteString(Name);
@ -46,9 +70,11 @@ namespace ZeroLevel.DocumentObjectModel
Type = reader.ReadString(); Type = reader.ReadString();
Tag = reader.ReadString(); Tag = reader.ReadString();
} }
#endregion
#endregion IBinarySerializable
#region IEquatable #region IEquatable
public bool Equals(Header other) public bool Equals(Header other)
{ {
if (other == null) return false; if (other == null) return false;
@ -58,9 +84,11 @@ namespace ZeroLevel.DocumentObjectModel
if (string.Compare(this.Tag, other.Tag, StringComparison.Ordinal) != 0) return false; if (string.Compare(this.Tag, other.Tag, StringComparison.Ordinal) != 0) return false;
return true; return true;
} }
#endregion
#endregion IEquatable
#region Equals & Hash #region Equals & Hash
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
return this.Equals(obj as Header); return this.Equals(obj as Header);
@ -73,13 +101,16 @@ namespace ZeroLevel.DocumentObjectModel
Type.GetHashCode() ^ Type.GetHashCode() ^
Tag.GetHashCode(); Tag.GetHashCode();
} }
#endregion
#endregion Equals & Hash
#region ICloneable #region ICloneable
public object Clone() public object Clone()
{ {
return new Header(this); return new Header(this);
} }
#endregion
#endregion ICloneable
} }
} }

@ -5,25 +5,36 @@ namespace ZeroLevel.DocumentObjectModel
public class Identifier : public class Identifier :
IBinarySerializable IBinarySerializable
{ {
public Identifier() { } public Identifier()
public Identifier(IBinaryReader reader) { Deserialize(reader); } {
}
public Identifier(IBinaryReader reader)
{
Deserialize(reader);
}
#region Fields #region Fields
/// <summary> /// <summary>
/// Version /// Version
/// </summary> /// </summary>
public int Version; public int Version;
/// <summary> /// <summary>
/// Timestamp ID /// Timestamp ID
/// </summary> /// </summary>
public long Timestamp; public long Timestamp;
/// <summary> /// <summary>
/// Label with day accurcy /// Label with day accurcy
/// </summary> /// </summary>
public string DateLabel; public string DateLabel;
#endregion
#endregion Fields
#region IBinarySerializable #region IBinarySerializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteInt32(this.Version); writer.WriteInt32(this.Version);
@ -37,6 +48,7 @@ namespace ZeroLevel.DocumentObjectModel
this.Timestamp = reader.ReadLong(); this.Timestamp = reader.ReadLong();
this.DateLabel = reader.ReadString(); this.DateLabel = reader.ReadString();
} }
#endregion
#endregion IBinarySerializable
} }
} }

@ -8,8 +8,10 @@ namespace ZeroLevel.DocumentObjectModel
{ {
[Description("Normal")] [Description("Normal")]
Normal = 0, Normal = 0,
[Description("Express")] [Description("Express")]
Express = 1, Express = 1,
[Description("Flash")] [Description("Flash")]
Flash = 2 Flash = 2
} }

@ -6,11 +6,14 @@ namespace ZeroLevel.DocumentObjectModel
IBinarySerializable IBinarySerializable
{ {
#region Fields #region Fields
public string Name; public string Name;
public string Value; public string Value;
#endregion
#endregion Fields
#region IBinarySerializable #region IBinarySerializable
public void Deserialize(IBinaryReader reader) public void Deserialize(IBinaryReader reader)
{ {
this.Name = reader.ReadString(); this.Name = reader.ReadString();
@ -22,6 +25,7 @@ namespace ZeroLevel.DocumentObjectModel
writer.WriteString(this.Name); writer.WriteString(this.Name);
writer.WriteString(this.Value); writer.WriteString(this.Value);
} }
#endregion
#endregion IBinarySerializable
} }
} }

@ -6,8 +6,15 @@ namespace ZeroLevel.DocumentObjectModel
public sealed class TagMetadata public sealed class TagMetadata
: IBinarySerializable : IBinarySerializable
{ {
public TagMetadata() { Initialize(); } public TagMetadata()
public TagMetadata(IBinaryReader reader) { Deserialize(reader); } {
Initialize();
}
public TagMetadata(IBinaryReader reader)
{
Deserialize(reader);
}
private void Initialize() private void Initialize()
{ {
@ -18,24 +25,30 @@ namespace ZeroLevel.DocumentObjectModel
} }
#region Fields #region Fields
/// <summary> /// <summary>
/// Placec (city, country, etc) /// Placec (city, country, etc)
/// </summary> /// </summary>
public List<Tag> Places; public List<Tag> Places;
/// <summary> /// <summary>
/// Companies /// Companies
/// </summary> /// </summary>
public List<Tag> Companies; public List<Tag> Companies;
/// <summary> /// <summary>
/// Persons /// Persons
/// </summary> /// </summary>
public List<Tag> Persons; public List<Tag> Persons;
/// <summary>Keywords /// <summary>Keywords
/// </summary> /// </summary>
public List<string> Keywords; public List<string> Keywords;
#endregion
#endregion Fields
#region IBinarySerializable #region IBinarySerializable
public void Serialize(IBinaryWriter writer) public void Serialize(IBinaryWriter writer)
{ {
writer.WriteCollection<Tag>(this.Companies); writer.WriteCollection<Tag>(this.Companies);
@ -51,6 +64,7 @@ namespace ZeroLevel.DocumentObjectModel
this.Places = reader.ReadCollection<Tag>(); this.Places = reader.ReadCollection<Tag>();
this.Persons = reader.ReadCollection<Tag>(); this.Persons = reader.ReadCollection<Tag>();
} }
#endregion
#endregion IBinarySerializable
} }
} }

@ -26,7 +26,9 @@ namespace DOM.Services
} }
#region Helpers #region Helpers
#region Map #region Map
private readonly Dictionary<ContentElementType, HashSet<ContentElementType>> _includingMap = private readonly Dictionary<ContentElementType, HashSet<ContentElementType>> _includingMap =
new Dictionary<ContentElementType, HashSet<ContentElementType>> new Dictionary<ContentElementType, HashSet<ContentElementType>>
{ {
@ -158,7 +160,9 @@ namespace DOM.Services
} }
} }
}; };
#endregion
#endregion Map
/// <summary> /// <summary>
/// Verify that one element can be included as a child of the second element /// Verify that one element can be included as a child of the second element
/// </summary> /// </summary>
@ -166,6 +170,7 @@ namespace DOM.Services
{ {
return _includingMap[elementType].Contains(containerType); return _includingMap[elementType].Contains(containerType);
} }
/// <summary> /// <summary>
/// Writing element to content, dependent on current context. /// Writing element to content, dependent on current context.
/// </summary> /// </summary>
@ -182,15 +187,19 @@ namespace DOM.Services
case ContentElementType.Section: case ContentElementType.Section:
(current as Section).Parts.Add(element); (current as Section).Parts.Add(element);
break; break;
case ContentElementType.Paragraph: case ContentElementType.Paragraph:
(current as Paragraph).Parts.Add(element); (current as Paragraph).Parts.Add(element);
break; break;
case ContentElementType.List: case ContentElementType.List:
(current as List).Items.Add(element); (current as List).Items.Add(element);
break; break;
case ContentElementType.Row: case ContentElementType.Row:
(current as Row).Cells.Add(element); (current as Row).Cells.Add(element);
break; break;
case ContentElementType.Audioplayer: case ContentElementType.Audioplayer:
if (element.Type == ContentElementType.Text) if (element.Type == ContentElementType.Text)
{ {
@ -201,6 +210,7 @@ namespace DOM.Services
(current as Audioplayer).Tracks.Add(element as Audio); (current as Audioplayer).Tracks.Add(element as Audio);
} }
break; break;
case ContentElementType.Videoplayer: case ContentElementType.Videoplayer:
if (element.Type == ContentElementType.Text) if (element.Type == ContentElementType.Text)
{ {
@ -211,6 +221,7 @@ namespace DOM.Services
(current as Videoplayer).Playlist.Add(element as Video); (current as Videoplayer).Playlist.Add(element as Video);
} }
break; break;
case ContentElementType.Gallery: case ContentElementType.Gallery:
if (element.Type == ContentElementType.Text) if (element.Type == ContentElementType.Text)
{ {
@ -221,6 +232,7 @@ namespace DOM.Services
(current as Gallery).Images.Add(element as Image); (current as Gallery).Images.Add(element as Image);
} }
break; break;
case ContentElementType.Table: case ContentElementType.Table:
if (element.Type == ContentElementType.Column) if (element.Type == ContentElementType.Column)
{ {
@ -254,35 +266,45 @@ namespace DOM.Services
case ContentElementType.Section: case ContentElementType.Section:
LeaveSection(); LeaveSection();
break; break;
case ContentElementType.Paragraph: case ContentElementType.Paragraph:
LeaveParagraph(); LeaveParagraph();
break; break;
case ContentElementType.Audioplayer: case ContentElementType.Audioplayer:
LeaveAudioplayer(); LeaveAudioplayer();
break; break;
case ContentElementType.Videoplayer: case ContentElementType.Videoplayer:
LeaveVideoplayer(); LeaveVideoplayer();
break; break;
case ContentElementType.Gallery: case ContentElementType.Gallery:
LeaveGallery(); LeaveGallery();
break; break;
case ContentElementType.List: case ContentElementType.List:
LeaveList(); LeaveList();
break; break;
case ContentElementType.Table: case ContentElementType.Table:
LeaveTable(); LeaveTable();
break; break;
case ContentElementType.Row: case ContentElementType.Row:
LeaveRow(); LeaveRow();
break; break;
default: default:
throw new Exception($"Uncknown container type {current.Type}"); throw new Exception($"Uncknown container type {current.Type}");
} }
} }
} }
#endregion
#endregion Helpers
#region Containers #region Containers
public void EnterSection() public void EnterSection()
{ {
ReduceContainers(); ReduceContainers();
@ -379,9 +401,11 @@ namespace DOM.Services
} }
WriteElement(videoplayer); WriteElement(videoplayer);
} }
#endregion
#endregion Containers
#region List #region List
public void EnterList() public void EnterList()
{ {
if (_containers.Count == 0) EnterSection(); if (_containers.Count == 0) EnterSection();
@ -403,9 +427,11 @@ namespace DOM.Services
} }
WriteElement(list); WriteElement(list);
} }
#endregion
#endregion List
#region Table #region Table
public void EnterTable(string name, string summary) public void EnterTable(string name, string summary)
{ {
if (_containers.Count == 0) EnterSection(); if (_containers.Count == 0) EnterSection();
@ -449,9 +475,11 @@ namespace DOM.Services
} }
WriteElement(table); WriteElement(table);
} }
#endregion
#endregion Table
#region Primitives #region Primitives
public void WriteColumn(Column column) public void WriteColumn(Column column)
{ {
if (column == null) if (column == null)
@ -469,18 +497,22 @@ namespace DOM.Services
} }
WriteElement(text); WriteElement(text);
} }
public void WriteText(string text) public void WriteText(string text)
{ {
WriteElement(new Text(text)); WriteElement(new Text(text));
} }
public void WriteText(string text, TextStyle style) public void WriteText(string text, TextStyle style)
{ {
WriteElement(new Text(text) { Style = style }); WriteElement(new Text(text) { Style = style });
} }
public void WriteHeader(string text) public void WriteHeader(string text)
{ {
WriteElement(new 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) public void WriteQuote(Quote quote)
{ {
if (quote == null) if (quote == null)
@ -489,10 +521,12 @@ namespace DOM.Services
} }
WriteElement(quote); WriteElement(quote);
} }
public void WriteQuote(string quote) public void WriteQuote(string quote)
{ {
WriteElement(new Quote(quote)); WriteElement(new Quote(quote));
} }
public void WriteLink(Link link) public void WriteLink(Link link)
{ {
if (link == null) if (link == null)
@ -501,10 +535,12 @@ namespace DOM.Services
} }
WriteElement(link); WriteElement(link);
} }
public void WriteLink(string href, string value) public void WriteLink(string href, string value)
{ {
WriteElement(new Link(href, value)); WriteElement(new Link(href, value));
} }
public void WriteForm(FormContent form) public void WriteForm(FormContent form)
{ {
if (form == null) if (form == null)
@ -513,6 +549,7 @@ namespace DOM.Services
} }
WriteElement(form); WriteElement(form);
} }
public void WriteImage(Image image) public void WriteImage(Image image)
{ {
if (image == null) if (image == null)
@ -521,6 +558,7 @@ namespace DOM.Services
} }
WriteElement(image); WriteElement(image);
} }
public void WriteAudio(Audio audio) public void WriteAudio(Audio audio)
{ {
if (audio == null) if (audio == null)
@ -529,6 +567,7 @@ namespace DOM.Services
} }
WriteElement(audio); WriteElement(audio);
} }
public void WriteVideo(Video video) public void WriteVideo(Video video)
{ {
if (video == null) if (video == null)
@ -537,7 +576,8 @@ namespace DOM.Services
} }
WriteElement(video); WriteElement(video);
} }
#endregion
#endregion Primitives
public void Complete() public void Complete()
{ {

@ -19,31 +19,43 @@ namespace DOM.Services
// Primitives // Primitives
case ContentElementType.Text: case ContentElementType.Text:
return new ZeroLevel.DocumentObjectModel.Flow.Text(reader); return new ZeroLevel.DocumentObjectModel.Flow.Text(reader);
case ContentElementType.Quote: case ContentElementType.Quote:
return new Quote(reader); return new Quote(reader);
case ContentElementType.Link: case ContentElementType.Link:
return new Link(reader); return new Link(reader);
case ContentElementType.Image: case ContentElementType.Image:
return new Image(reader); return new Image(reader);
case ContentElementType.Audio: case ContentElementType.Audio:
return new Audio(reader); return new Audio(reader);
case ContentElementType.Video: case ContentElementType.Video:
return new Video(reader); return new Video(reader);
// Containers // Containers
case ContentElementType.Row: case ContentElementType.Row:
return new Row(reader); return new Row(reader);
case ContentElementType.Paragraph: case ContentElementType.Paragraph:
return new Paragraph(reader); return new Paragraph(reader);
case ContentElementType.Section: case ContentElementType.Section:
return new Section(reader); return new Section(reader);
case ContentElementType.List: case ContentElementType.List:
return new List(reader); return new List(reader);
case ContentElementType.Table: case ContentElementType.Table:
return new Table(reader); return new Table(reader);
case ContentElementType.Gallery: case ContentElementType.Gallery:
return new Gallery(reader); return new Gallery(reader);
case ContentElementType.Audioplayer: case ContentElementType.Audioplayer:
return new Audioplayer(reader); return new Audioplayer(reader);
case ContentElementType.Videoplayer: case ContentElementType.Videoplayer:
return new Videoplayer(reader); return new Videoplayer(reader);
// Feature // Feature

@ -19,25 +19,31 @@ namespace DOM.Services
case ContentElementType.Text: case ContentElementType.Text:
reader.ReadText(element as ZeroLevel.DocumentObjectModel.Flow.Text); reader.ReadText(element as ZeroLevel.DocumentObjectModel.Flow.Text);
break; break;
case ContentElementType.Quote: case ContentElementType.Quote:
reader.ReadQuote(element as Quote); reader.ReadQuote(element as Quote);
break; break;
case ContentElementType.Link: case ContentElementType.Link:
counter.IncLinkId(); counter.IncLinkId();
reader.ReadLink(element as Link, counter.LinkId); reader.ReadLink(element as Link, counter.LinkId);
break; break;
case ContentElementType.Image: case ContentElementType.Image:
counter.IncImageId(); counter.IncImageId();
reader.ReadImage(element as Image, counter.ImageId); reader.ReadImage(element as Image, counter.ImageId);
break; break;
case ContentElementType.Audio: case ContentElementType.Audio:
counter.IncAudioId(); counter.IncAudioId();
reader.ReadAudio(element as Audio, counter.AudioId); reader.ReadAudio(element as Audio, counter.AudioId);
break; break;
case ContentElementType.Video: case ContentElementType.Video:
counter.IncVideoId(); counter.IncVideoId();
reader.ReadVideo(element as Video, counter.VideoId); reader.ReadVideo(element as Video, counter.VideoId);
break; break;
case ContentElementType.Form: case ContentElementType.Form:
reader.ReadForm(element as FormContent); reader.ReadForm(element as FormContent);
break; break;
@ -52,6 +58,7 @@ namespace DOM.Services
} }
} }
break; break;
case ContentElementType.Section: case ContentElementType.Section:
var section = (element as Section); var section = (element as Section);
reader.EnterSection(section); reader.EnterSection(section);
@ -61,6 +68,7 @@ namespace DOM.Services
} }
reader.LeaveSection(section); reader.LeaveSection(section);
break; break;
case ContentElementType.Paragraph: case ContentElementType.Paragraph:
var paragraph = (element as Paragraph); var paragraph = (element as Paragraph);
reader.EnterParagraph(paragraph); reader.EnterParagraph(paragraph);
@ -70,6 +78,7 @@ namespace DOM.Services
} }
reader.LeaveParagraph(paragraph); reader.LeaveParagraph(paragraph);
break; break;
case ContentElementType.List: case ContentElementType.List:
var list = (element as List); var list = (element as List);
reader.EnterList(list); reader.EnterList(list);
@ -81,6 +90,7 @@ namespace DOM.Services
} }
reader.LeaveList(list); reader.LeaveList(list);
break; break;
case ContentElementType.Gallery: case ContentElementType.Gallery:
var gallery = (element as Gallery); var gallery = (element as Gallery);
reader.EnterGallery(gallery); reader.EnterGallery(gallery);
@ -90,6 +100,7 @@ namespace DOM.Services
} }
reader.LeaveGallery(gallery); reader.LeaveGallery(gallery);
break; break;
case ContentElementType.Audioplayer: case ContentElementType.Audioplayer:
var audioplayer = (element as Audioplayer); var audioplayer = (element as Audioplayer);
reader.EnterAudioplayer(audioplayer); reader.EnterAudioplayer(audioplayer);
@ -99,6 +110,7 @@ namespace DOM.Services
} }
reader.LeaveAudioplayer(audioplayer); reader.LeaveAudioplayer(audioplayer);
break; break;
case ContentElementType.Videoplayer: case ContentElementType.Videoplayer:
var videoplayer = (element as Videoplayer); var videoplayer = (element as Videoplayer);
reader.EnterVideoplayer(videoplayer); reader.EnterVideoplayer(videoplayer);
@ -108,6 +120,7 @@ namespace DOM.Services
} }
reader.LeaveVideoplayer(videoplayer); reader.LeaveVideoplayer(videoplayer);
break; break;
case ContentElementType.Table: case ContentElementType.Table:
var table = (element as Table); var table = (element as Table);
reader.EnterTable(table); reader.EnterTable(table);
@ -133,6 +146,7 @@ namespace DOM.Services
break; break;
} }
} }
/// <summary> /// <summary>
/// Reading metadata items /// Reading metadata items
/// </summary> /// </summary>
@ -214,6 +228,7 @@ namespace DOM.Services
reader.LeaveCategories(doc.Categories); reader.LeaveCategories(doc.Categories);
return reader.Complete(); return reader.Complete();
} }
/// <summary> /// <summary>
/// Reading content elements /// Reading content elements
/// </summary> /// </summary>

@ -12,6 +12,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
IContainer IContainer
{ {
#region Activator #region Activator
private static object Activate(Type type, object[] args) private static object Activate(Type type, object[] args)
{ {
var flags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public; var flags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public;
@ -78,11 +79,14 @@ namespace ZeroLevel.Patterns.DependencyInjection
Compose(instance); Compose(instance);
return instance; return instance;
} }
#endregion
#endregion Activator
#region Caching #region Caching
private readonly ReaderWriterLockSlim _rwLock = private readonly ReaderWriterLockSlim _rwLock =
new ReaderWriterLockSlim(); new ReaderWriterLockSlim();
/// <summary> /// <summary>
/// Map - contract - dependency resolving /// Map - contract - dependency resolving
/// </summary> /// </summary>
@ -90,14 +94,17 @@ namespace ZeroLevel.Patterns.DependencyInjection
new Dictionary<Type, List<ResolveTypeInfo>>(); new Dictionary<Type, List<ResolveTypeInfo>>();
private readonly object _constructorCacheeLocker = new object(); private readonly object _constructorCacheeLocker = new object();
/// <summary> /// <summary>
/// Types constructors cache /// Types constructors cache
/// </summary> /// </summary>
private readonly Dictionary<Type, IEnumerable<ConstructorMetadata>> _constructorCachee = private readonly Dictionary<Type, IEnumerable<ConstructorMetadata>> _constructorCachee =
new Dictionary<Type, IEnumerable<ConstructorMetadata>>(); new Dictionary<Type, IEnumerable<ConstructorMetadata>>();
#endregion
#endregion Caching
#region Private #region Private
/// <summary> /// <summary>
/// Creating an instance of an object at the specified dependency resolution /// Creating an instance of an object at the specified dependency resolution
/// </summary> /// </summary>
@ -126,6 +133,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
} }
return sessionInstance; return sessionInstance;
} }
/// <summary> /// <summary>
/// Creating an instance of the object at the specified dependency resolution, for a generic type of contract /// Creating an instance of the object at the specified dependency resolution, for a generic type of contract
/// </summary> /// </summary>
@ -170,6 +178,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
} }
return sessionInstance; return sessionInstance;
} }
/// <summary> /// <summary>
/// Collecting properties of the type marked with attribute dependency resolution /// Collecting properties of the type marked with attribute dependency resolution
/// </summary> /// </summary>
@ -180,6 +189,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
return type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy). return type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy).
Where(p => p.GetCustomAttribute<ResolveAttribute>() != null); Where(p => p.GetCustomAttribute<ResolveAttribute>() != null);
} }
/// <summary> /// <summary>
/// Collecting fields of type marked with an attribute of dependency resolution /// Collecting fields of type marked with an attribute of dependency resolution
/// </summary> /// </summary>
@ -190,6 +200,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
return type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy). return type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy).
Where(p => p.GetCustomAttribute<ResolveAttribute>() != null); Where(p => p.GetCustomAttribute<ResolveAttribute>() != null);
} }
/// <summary> /// <summary>
/// Search for dependency resolution /// Search for dependency resolution
/// </summary> /// </summary>
@ -229,6 +240,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
} }
throw new KeyNotFoundException($"Can't resolve dependency by type '{type.FullName}' and dependency name '{resolveName}'"); throw new KeyNotFoundException($"Can't resolve dependency by type '{type.FullName}' and dependency name '{resolveName}'");
} }
/// <summary> /// <summary>
/// Resolving dependency on attribute "Resolve /// Resolving dependency on attribute "Resolve
/// </summary> /// </summary>
@ -258,6 +270,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
throw new Exception($"Can't create type '{type.FullName}' instance for contract type {type.FullName}. Dependency key: '{resolveAttribute?.ResolveName}'", ex); throw new Exception($"Can't create type '{type.FullName}' instance for contract type {type.FullName}. Dependency key: '{resolveAttribute?.ResolveName}'", ex);
} }
} }
/// <summary> /// <summary>
/// Collection of interfaces and abstract classes from which the type is inherited /// Collection of interfaces and abstract classes from which the type is inherited
/// </summary> /// </summary>
@ -275,6 +288,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
} }
return interfaces; return interfaces;
} }
/// <summary> /// <summary>
/// Getting a list of metadata by type constructors /// Getting a list of metadata by type constructors
/// </summary> /// </summary>
@ -297,6 +311,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
} }
return _constructorCachee[type]; return _constructorCachee[type];
} }
/// <summary> /// <summary>
/// Creating an instance of an object, including with non-public constructors /// Creating an instance of an object, including with non-public constructors
/// </summary> /// </summary>
@ -327,6 +342,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
return Activator.CreateInstance(type, flags, null, args, culture);*/ return Activator.CreateInstance(type, flags, null, args, culture);*/
} }
} }
/// <summary> /// <summary>
/// Dependency resolution registration /// Dependency resolution registration
/// </summary> /// </summary>
@ -377,9 +393,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
_rwLock.ExitUpgradeableReadLock(); _rwLock.ExitUpgradeableReadLock();
} }
} }
#endregion
#endregion Private
#region Register #region Register
public void Register<TContract, TImplementation>() public void Register<TContract, TImplementation>()
{ {
var resolveType = new ResolveTypeInfo var resolveType = new ResolveTypeInfo
@ -475,9 +493,13 @@ namespace ZeroLevel.Patterns.DependencyInjection
}; };
Register(contractType, resolveType); Register(contractType, resolveType);
} }
#endregion
#endregion Register
#region Register with parameters #region Register with parameters
public void ParameterizedRegister<TContract, TImplementation>(object[] constructorParameters) public void ParameterizedRegister<TContract, TImplementation>(object[] constructorParameters)
{ {
var resolveType = new ResolveTypeInfo var resolveType = new ResolveTypeInfo
@ -581,9 +603,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
}; };
Register(contractType, resolveType); Register(contractType, resolveType);
} }
#endregion
#endregion Register with parameters
#region Register instance #region Register instance
/// <summary> /// <summary>
/// Register singletone /// Register singletone
/// </summary> /// </summary>
@ -601,6 +625,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
}; };
Register(typeof(TContract), resolveType); Register(typeof(TContract), resolveType);
} }
public void Register(Type contractType, object implementation) public void Register(Type contractType, object implementation)
{ {
var resolveType = new ResolveTypeInfo var resolveType = new ResolveTypeInfo
@ -613,6 +638,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
}; };
Register(contractType, resolveType); Register(contractType, resolveType);
} }
public void Register<TContract>(TContract implementation, string resolveName) public void Register<TContract>(TContract implementation, string resolveName)
{ {
var resolveType = new ResolveTypeInfo var resolveType = new ResolveTypeInfo
@ -625,6 +651,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
}; };
Register(typeof(TContract), resolveType); Register(typeof(TContract), resolveType);
} }
public void Register(Type contractType, string resolveName, object implementation) public void Register(Type contractType, string resolveName, object implementation)
{ {
var resolveType = new ResolveTypeInfo var resolveType = new ResolveTypeInfo
@ -637,9 +664,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
}; };
Register(contractType, resolveType); Register(contractType, resolveType);
} }
#endregion
#endregion Register instance
#region Safe register #region Safe register
public bool TryRegister<TContract, TImplementation>(Action<Exception> fallback = null) public bool TryRegister<TContract, TImplementation>(Action<Exception> fallback = null)
{ {
try try
@ -751,9 +780,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
return false; return false;
} }
} }
#endregion
#endregion Safe register
#region Safe register with parameters #region Safe register with parameters
public bool TryParameterizedRegister<TContract, TImplementation>(object[] constructorParameters, Action<Exception> fallback = null) public bool TryParameterizedRegister<TContract, TImplementation>(object[] constructorParameters, Action<Exception> fallback = null)
{ {
try try
@ -865,9 +896,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
return false; return false;
} }
} }
#endregion
#endregion Safe register with parameters
#region Resolving #region Resolving
public object Resolve(Type type, bool compose = true) public object Resolve(Type type, bool compose = true)
{ {
return Resolve(type, string.Empty, null, compose); return Resolve(type, string.Empty, null, compose);
@ -971,9 +1004,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
throw new Exception($"Can't create instance for type {type.FullName} for resolved dependency {type.FullName} by key {resolveName}", ex); throw new Exception($"Can't create instance for type {type.FullName} for resolved dependency {type.FullName} by key {resolveName}", ex);
} }
} }
#endregion
#endregion Resolving
#region Safe resolving #region Safe resolving
public object TryResolve(Type type, out object result, bool compose = true) public object TryResolve(Type type, out object result, bool compose = true)
{ {
return TryResolve(type, string.Empty, null, out result, compose); return TryResolve(type, string.Empty, null, out result, compose);
@ -1066,9 +1101,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
result = null; result = null;
return false; return false;
} }
#endregion
#endregion Safe resolving
#region Composition #region Composition
/// <summary> /// <summary>
/// Filling in the fields and properties of an object with auto-set values flagged from the container parameters /// Filling in the fields and properties of an object with auto-set values flagged from the container parameters
/// </summary> /// </summary>
@ -1162,9 +1199,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
} }
return false; return false;
} }
#endregion
#endregion Composition
#region IDisposable #region IDisposable
public void Dispose() public void Dispose()
{ {
try try
@ -1190,7 +1229,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
{ {
(gitem as IDisposable)?.Dispose(); (gitem as IDisposable)?.Dispose();
} }
catch(Exception ex) catch (Exception ex)
{ {
Log.SystemError(ex, $"[Container] Generic singletone dispose error. Instance: '{gitem?.GetType()?.FullName ?? string.Empty}'"); Log.SystemError(ex, $"[Container] Generic singletone dispose error. Instance: '{gitem?.GetType()?.FullName ?? string.Empty}'");
} }
@ -1208,9 +1247,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
_rwLock.ExitWriteLock(); _rwLock.ExitWriteLock();
} }
} }
#endregion
#endregion IDisposable
#region IEverythingStorage #region IEverythingStorage
private readonly Lazy<IEverythingStorage> _everything = private readonly Lazy<IEverythingStorage> _everything =
new Lazy<IEverythingStorage>(EverythingStorage.Create); new Lazy<IEverythingStorage>(EverythingStorage.Create);
@ -1218,18 +1259,22 @@ namespace ZeroLevel.Patterns.DependencyInjection
{ {
_everything.Value.Add<T>(key, value); _everything.Value.Add<T>(key, value);
} }
public void Remove<T>(string key) public void Remove<T>(string key)
{ {
_everything.Value.Remove<T>(key); _everything.Value.Remove<T>(key);
} }
public bool Contains<T>(string key) public bool Contains<T>(string key)
{ {
return _everything.Value.ContainsKey<T>(key); return _everything.Value.ContainsKey<T>(key);
} }
public bool TrySave<T>(string key, T value) public bool TrySave<T>(string key, T value)
{ {
return _everything.Value.TryAdd<T>(key, value); return _everything.Value.TryAdd<T>(key, value);
} }
public bool TryRemove<T>(string key) public bool TryRemove<T>(string key)
{ {
return _everything.Value.TryRemove<T>(key); return _everything.Value.TryRemove<T>(key);
@ -1265,6 +1310,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
return _everything.Value.Get<T>(key); return _everything.Value.Get<T>(key);
return defaultValue; return defaultValue;
} }
#endregion
#endregion IEverythingStorage
} }
} }

@ -8,6 +8,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
public sealed class ContainerFactory : IContainerFactory public sealed class ContainerFactory : IContainerFactory
{ {
#region Private #region Private
private bool _disposed = false; private bool _disposed = false;
private static string GetKey(string key) private static string GetKey(string key)
@ -21,9 +22,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
private readonly ConcurrentDictionary<string, IContainer> _containers = private readonly ConcurrentDictionary<string, IContainer> _containers =
new ConcurrentDictionary<string, IContainer>(); new ConcurrentDictionary<string, IContainer>();
#endregion
#endregion Private
#region Public #region Public
public IContainer this[string containerName] public IContainer this[string containerName]
{ {
get get
@ -105,9 +108,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
} }
return false; return false;
} }
#endregion
#endregion Public
#region IDisposable #region IDisposable
public void Dispose() public void Dispose()
{ {
if (false == _disposed) if (false == _disposed)
@ -120,6 +125,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
_containers.Clear(); _containers.Clear();
} }
} }
#endregion
#endregion IDisposable
} }
} }

@ -6,17 +6,20 @@
public interface ICompositionProvider public interface ICompositionProvider
{ {
#region Composition #region Composition
/// <summary> /// <summary>
/// Object compositions, insert contract implementation /// Object compositions, insert contract implementation
/// </summary> /// </summary>
/// <param name="instanse">Object instance</param> /// <param name="instanse">Object instance</param>
void Compose(object instanse, bool recursive = true); void Compose(object instanse, bool recursive = true);
/// <summary> /// <summary>
/// Object compositions, insert contract implementation /// Object compositions, insert contract implementation
/// </summary> /// </summary>
/// <param name="instanse">Object instance</param> /// <param name="instanse">Object instance</param>
/// /// <returns>false if composition fault</returns> /// /// <returns>false if composition fault</returns>
bool TryCompose(object instanse, bool recursive = true); bool TryCompose(object instanse, bool recursive = true);
#endregion
#endregion Composition
} }
} }

@ -11,8 +11,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
IDisposable IDisposable
{ {
bool IsResolvingExists<T>(); bool IsResolvingExists<T>();
bool IsResolvingExists<T>(string resolveName); bool IsResolvingExists<T>(string resolveName);
bool IsResolvingExists(Type type); bool IsResolvingExists(Type type);
bool IsResolvingExists(Type type, string resolveName); bool IsResolvingExists(Type type, string resolveName);
} }
} }

@ -6,16 +6,23 @@ namespace ZeroLevel.Patterns.DependencyInjection
public interface IContainerFactory : IDisposable public interface IContainerFactory : IDisposable
{ {
#region Properties #region Properties
IContainer this[string containerName] { get; } IContainer this[string containerName] { get; }
IEnumerable<string> ContainerNames { get; } IEnumerable<string> ContainerNames { get; }
IEnumerable<IContainer> Containers { get; } IEnumerable<IContainer> Containers { get; }
#endregion
#endregion Properties
#region Methods #region Methods
IContainer CreateContainer(string containerName); IContainer CreateContainer(string containerName);
IContainer GetContainer(string containerName); IContainer GetContainer(string containerName);
bool Contains(string containerName); bool Contains(string containerName);
bool Remove(string containerName); bool Remove(string containerName);
#endregion
#endregion Methods
} }
} }

@ -9,12 +9,14 @@ namespace ZeroLevel.Patterns.DependencyInjection
public interface IContainerInstanceRegister public interface IContainerInstanceRegister
{ {
#region Register instance #region Register instance
/// <summary> /// <summary>
/// Register instance for contract <typeparamref name="TContract"/>. (singletone) /// Register instance for contract <typeparamref name="TContract"/>. (singletone)
/// </summary> /// </summary>
/// <typeparam name="TContract">Contract</typeparam> /// <typeparam name="TContract">Contract</typeparam>
/// <param name="implementation">Instance</param> /// <param name="implementation">Instance</param>
void Register<TContract>(TContract implementation); void Register<TContract>(TContract implementation);
/// <summary> /// <summary>
/// Register instance for contract <typeparamref name="TContract"/>. (singletone) /// Register instance for contract <typeparamref name="TContract"/>. (singletone)
/// </summary> /// </summary>
@ -22,12 +24,14 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="implementation">Instance</param> /// <param name="implementation">Instance</param>
/// <param name="resolveName">Dependency name</param> /// <param name="resolveName">Dependency name</param>
void Register<TContract>(TContract implementation, string resolveName); void Register<TContract>(TContract implementation, string resolveName);
/// <summary> /// <summary>
/// Register instance for contract (singletone) /// Register instance for contract (singletone)
/// </summary> /// </summary>
/// <param name="contractType">Contract</param> /// <param name="contractType">Contract</param>
/// <param name="implementation">Instance</param> /// <param name="implementation">Instance</param>
void Register(Type contractType, object implementation); void Register(Type contractType, object implementation);
/// <summary> /// <summary>
/// Register instance for contract (singletone) /// Register instance for contract (singletone)
/// </summary> /// </summary>
@ -35,6 +39,8 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="resolveName">Dependency name</param> /// <param name="resolveName">Dependency name</param>
/// <param name="implementation">Instance</param> /// <param name="implementation">Instance</param>
void Register(Type contractType, string resolveName, object implementation); void Register(Type contractType, string resolveName, object implementation);
#endregion
#endregion Register instance
} }
} }

@ -9,12 +9,14 @@ namespace ZeroLevel.Patterns.DependencyInjection
public interface IContainerRegister : IDisposable public interface IContainerRegister : IDisposable
{ {
#region Register #region Register
/// <summary> /// <summary>
/// Dependency resolution registration /// Dependency resolution registration
/// </summary> /// </summary>
/// <typeparam name="TContract">Contract</typeparam> /// <typeparam name="TContract">Contract</typeparam>
/// <typeparam name="TImplementation">Dependency resolution</typeparam> /// <typeparam name="TImplementation">Dependency resolution</typeparam>
void Register<TContract, TImplementation>(); void Register<TContract, TImplementation>();
/// <summary> /// <summary>
/// Dependency resolution registration /// Dependency resolution registration
/// </summary> /// </summary>
@ -22,6 +24,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <typeparam name="TImplementation">Dependency resolution</typeparam> /// <typeparam name="TImplementation">Dependency resolution</typeparam>
/// <param name="resolveName">Dependency name</param> /// <param name="resolveName">Dependency name</param>
void Register<TContract, TImplementation>(string resolveName); void Register<TContract, TImplementation>(string resolveName);
/// <summary> /// <summary>
/// Dependency resolution registration /// Dependency resolution registration
/// </summary> /// </summary>
@ -29,6 +32,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <typeparam name="TImplementation">Dependency resolution</typeparam> /// <typeparam name="TImplementation">Dependency resolution</typeparam>
/// <param name="shared">true - for singletone</param> /// <param name="shared">true - for singletone</param>
void Register<TContract, TImplementation>(bool shared); void Register<TContract, TImplementation>(bool shared);
/// <summary> /// <summary>
/// Dependency resolution registration /// Dependency resolution registration
/// </summary> /// </summary>
@ -44,6 +48,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="contractType">Contract</param> /// <param name="contractType">Contract</param>
/// <param name="implementationType">Dependency resolution</param> /// <param name="implementationType">Dependency resolution</param>
void Register(Type contractType, Type implementationType); void Register(Type contractType, Type implementationType);
/// <summary> /// <summary>
/// Dependency resolution registration /// Dependency resolution registration
/// </summary> /// </summary>
@ -51,6 +56,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="implementationType">Dependency resolution</param> /// <param name="implementationType">Dependency resolution</param>
/// <param name="resolveName">Dependency name</param> /// <param name="resolveName">Dependency name</param>
void Register(Type contractType, Type implementationType, string resolveName); void Register(Type contractType, Type implementationType, string resolveName);
/// <summary> /// <summary>
/// Dependency resolution registration /// Dependency resolution registration
/// </summary> /// </summary>
@ -58,6 +64,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="implementationType">Dependency resolution</param> /// <param name="implementationType">Dependency resolution</param>
/// <param name="shared">true - for singletone</param> /// <param name="shared">true - for singletone</param>
void Register(Type contractType, Type implementationType, bool shared); void Register(Type contractType, Type implementationType, bool shared);
/// <summary> /// <summary>
/// Dependency resolution registration /// Dependency resolution registration
/// </summary> /// </summary>
@ -66,9 +73,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="resolveName">Dependency name</param> /// <param name="resolveName">Dependency name</param>
/// <param name="shared">true - for singletone</param> /// <param name="shared">true - for singletone</param>
void Register(Type contractType, Type implementationType, string resolveName, bool shared); void Register(Type contractType, Type implementationType, string resolveName, bool shared);
#endregion
#endregion Register
#region Register with parameters #region Register with parameters
/// <summary> /// <summary>
/// Dependency resolution registration with constructor parameters /// Dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -76,6 +85,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <typeparam name="TImplementation">Dependency resolution</typeparam> /// <typeparam name="TImplementation">Dependency resolution</typeparam>
/// <param name="constructorParameters">Ctor args</param> /// <param name="constructorParameters">Ctor args</param>
void ParameterizedRegister<TContract, TImplementation>(object[] constructorParameters); void ParameterizedRegister<TContract, TImplementation>(object[] constructorParameters);
/// <summary> /// <summary>
/// Dependency resolution registration with constructor parameters /// Dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -84,6 +94,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="resolveName">Dependency name</param> /// <param name="resolveName">Dependency name</param>
/// <param name="constructorParameters">Ctor args</param> /// <param name="constructorParameters">Ctor args</param>
void ParameterizedRegister<TContract, TImplementation>(string resolveName, object[] constructorParameters); void ParameterizedRegister<TContract, TImplementation>(string resolveName, object[] constructorParameters);
/// <summary> /// <summary>
/// Dependency resolution registration with constructor parameters /// Dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -92,6 +103,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="shared">true - for singletone</param> /// <param name="shared">true - for singletone</param>
/// <param name="constructorParameters">Ctor args</param> /// <param name="constructorParameters">Ctor args</param>
void ParameterizedRegister<TContract, TImplementation>(bool shared, object[] constructorParameters); void ParameterizedRegister<TContract, TImplementation>(bool shared, object[] constructorParameters);
/// <summary> /// <summary>
/// Dependency resolution registration with constructor parameters /// Dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -101,6 +113,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="shared">true - for singletone</param> /// <param name="shared">true - for singletone</param>
/// <param name="constructorParameters">Ctor args</param> /// <param name="constructorParameters">Ctor args</param>
void ParameterizedRegister<TContract, TImplementation>(string resolveName, bool shared, object[] constructorParameters); void ParameterizedRegister<TContract, TImplementation>(string resolveName, bool shared, object[] constructorParameters);
/// <summary> /// <summary>
/// Dependency resolution registration with constructor parameters /// Dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -108,6 +121,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="implementationType">Dependency resolution</param> /// <param name="implementationType">Dependency resolution</param>
/// <param name="constructorParameters">Ctor args</param> /// <param name="constructorParameters">Ctor args</param>
void ParameterizedRegister(Type contractType, Type implementationType, object[] constructorParameters); void ParameterizedRegister(Type contractType, Type implementationType, object[] constructorParameters);
/// <summary> /// <summary>
/// Dependency resolution registration with constructor parameters /// Dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -116,6 +130,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="resolveName">Dependency name</param> /// <param name="resolveName">Dependency name</param>
/// <param name="constructorParameters">Ctor args</param> /// <param name="constructorParameters">Ctor args</param>
void ParameterizedRegister(Type contractType, Type implementationType, string resolveName, object[] constructorParameters); void ParameterizedRegister(Type contractType, Type implementationType, string resolveName, object[] constructorParameters);
/// <summary> /// <summary>
/// Dependency resolution registration with constructor parameters /// Dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -124,6 +139,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="shared">true - for singletone</param> /// <param name="shared">true - for singletone</param>
/// <param name="constructorParameters">Ctor args</param> /// <param name="constructorParameters">Ctor args</param>
void ParameterizedRegister(Type contractType, Type implementationType, bool shared, object[] constructorParameters); void ParameterizedRegister(Type contractType, Type implementationType, bool shared, object[] constructorParameters);
/// <summary> /// <summary>
/// Dependency resolution registration with constructor parameters /// Dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -133,9 +149,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="shared">true - for singletone</param> /// <param name="shared">true - for singletone</param>
/// <param name="constructorParameters">Ctor args</param> /// <param name="constructorParameters">Ctor args</param>
void ParameterizedRegister(Type contractType, Type implementationType, string resolveName, bool shared, object[] constructorParameters); void ParameterizedRegister(Type contractType, Type implementationType, string resolveName, bool shared, object[] constructorParameters);
#endregion
#endregion Register with parameters
#region Safe register #region Safe register
/// <summary> /// <summary>
/// Safe dependency resolution registration /// Safe dependency resolution registration
/// </summary> /// </summary>
@ -144,6 +162,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryRegister<TContract, TImplementation>(Action<Exception> fallback = null); bool TryRegister<TContract, TImplementation>(Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration /// Safe dependency resolution registration
/// </summary> /// </summary>
@ -153,6 +172,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryRegister<TContract, TImplementation>(string resolveName, Action<Exception> fallback = null); bool TryRegister<TContract, TImplementation>(string resolveName, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration /// Safe dependency resolution registration
/// </summary> /// </summary>
@ -162,6 +182,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryRegister<TContract, TImplementation>(bool shared, Action<Exception> fallback = null); bool TryRegister<TContract, TImplementation>(bool shared, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration /// Safe dependency resolution registration
/// </summary> /// </summary>
@ -172,6 +193,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryRegister<TContract, TImplementation>(string resolveName, bool shared, Action<Exception> fallback = null); bool TryRegister<TContract, TImplementation>(string resolveName, bool shared, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration /// Safe dependency resolution registration
/// </summary> /// </summary>
@ -180,6 +202,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryRegister(Type contractType, Type implementationType, Action<Exception> fallback = null); bool TryRegister(Type contractType, Type implementationType, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration /// Safe dependency resolution registration
/// </summary> /// </summary>
@ -189,6 +212,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryRegister(Type contractType, Type implementationType, string resolveName, Action<Exception> fallback = null); bool TryRegister(Type contractType, Type implementationType, string resolveName, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration /// Safe dependency resolution registration
/// </summary> /// </summary>
@ -198,6 +222,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryRegister(Type contractType, Type implementationType, bool shared, Action<Exception> fallback = null); bool TryRegister(Type contractType, Type implementationType, bool shared, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration /// Safe dependency resolution registration
/// </summary> /// </summary>
@ -208,9 +233,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryRegister(Type contractType, Type implementationType, string resolveName, bool shared, Action<Exception> fallback = null); bool TryRegister(Type contractType, Type implementationType, string resolveName, bool shared, Action<Exception> fallback = null);
#endregion
#endregion Safe register
#region Safe register with parameters #region Safe register with parameters
/// <summary> /// <summary>
/// Safe dependency resolution registration with constructor parameters /// Safe dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -220,6 +247,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryParameterizedRegister<TContract, TImplementation>(object[] constructorParameters, Action<Exception> fallback = null); bool TryParameterizedRegister<TContract, TImplementation>(object[] constructorParameters, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration with constructor parameters /// Safe dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -230,6 +258,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryParameterizedRegister<TContract, TImplementation>(string resolveName, object[] constructorParameters, Action<Exception> fallback = null); bool TryParameterizedRegister<TContract, TImplementation>(string resolveName, object[] constructorParameters, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration with constructor parameters /// Safe dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -240,6 +269,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryParameterizedRegister<TContract, TImplementation>(bool shared, object[] constructorParameters, Action<Exception> fallback = null); bool TryParameterizedRegister<TContract, TImplementation>(bool shared, object[] constructorParameters, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration with constructor parameters /// Safe dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -251,6 +281,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryParameterizedRegister<TContract, TImplementation>(string resolveName, bool shared, object[] constructorParameters, Action<Exception> fallback = null); bool TryParameterizedRegister<TContract, TImplementation>(string resolveName, bool shared, object[] constructorParameters, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration with constructor parameters /// Safe dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -260,6 +291,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryParameterizedRegister(Type contractType, Type implementationType, object[] constructorParameters, Action<Exception> fallback = null); bool TryParameterizedRegister(Type contractType, Type implementationType, object[] constructorParameters, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration with constructor parameters /// Safe dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -270,6 +302,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryParameterizedRegister(Type contractType, Type implementationType, string resolveName, object[] constructorParameters, Action<Exception> fallback = null); bool TryParameterizedRegister(Type contractType, Type implementationType, string resolveName, object[] constructorParameters, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration with constructor parameters /// Safe dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -280,6 +313,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryParameterizedRegister(Type contractType, Type implementationType, bool shared, object[] constructorParameters, Action<Exception> fallback = null); bool TryParameterizedRegister(Type contractType, Type implementationType, bool shared, object[] constructorParameters, Action<Exception> fallback = null);
/// <summary> /// <summary>
/// Safe dependency resolution registration with constructor parameters /// Safe dependency resolution registration with constructor parameters
/// </summary> /// </summary>
@ -291,6 +325,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="fallback">Error handler</param> /// <param name="fallback">Error handler</param>
/// <returns>true - registration successfully completed</returns> /// <returns>true - registration successfully completed</returns>
bool TryParameterizedRegister(Type contractType, Type implementationType, string resolveName, bool shared, object[] constructorParameters, Action<Exception> fallback = null); bool TryParameterizedRegister(Type contractType, Type implementationType, string resolveName, bool shared, object[] constructorParameters, Action<Exception> fallback = null);
#endregion
#endregion Safe register with parameters
} }
} }

@ -8,6 +8,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
public interface IParameterStorage public interface IParameterStorage
{ {
#region IEverythingStorage #region IEverythingStorage
/// <summary> /// <summary>
/// Save parameter /// Save parameter
/// </summary> /// </summary>
@ -15,6 +16,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="key">Key</param> /// <param name="key">Key</param>
/// <param name="value">Parameter value</param> /// <param name="value">Parameter value</param>
void Save<T>(string key, T value); void Save<T>(string key, T value);
/// <summary> /// <summary>
/// Save or update parameter /// Save or update parameter
/// </summary> /// </summary>
@ -22,6 +24,7 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="key">Key</param> /// <param name="key">Key</param>
/// <param name="value">Parameter value</param> /// <param name="value">Parameter value</param>
void SaveOrUpdate<T>(string key, T value); void SaveOrUpdate<T>(string key, T value);
/// <summary> /// <summary>
/// Safe save parameter /// Safe save parameter
/// </summary> /// </summary>
@ -29,18 +32,21 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="key">Key</param> /// <param name="key">Key</param>
/// <param name="value">Parameter value</param> /// <param name="value">Parameter value</param>
bool TrySave<T>(string key, T value); bool TrySave<T>(string key, T value);
/// <summary> /// <summary>
/// Remove parameter by key /// Remove parameter by key
/// </summary> /// </summary>
/// <typeparam name="T">Parameter type</typeparam> /// <typeparam name="T">Parameter type</typeparam>
/// <param name="key">Key</param> /// <param name="key">Key</param>
void Remove<T>(string key); void Remove<T>(string key);
/// <summary> /// <summary>
/// Safe remove parameter by key /// Safe remove parameter by key
/// </summary> /// </summary>
/// <typeparam name="T">Parameter type</typeparam> /// <typeparam name="T">Parameter type</typeparam>
/// <param name="key">Key</param> /// <param name="key">Key</param>
bool TryRemove<T>(string key); bool TryRemove<T>(string key);
/// <summary> /// <summary>
/// Get parameter value by key /// Get parameter value by key
/// </summary> /// </summary>
@ -48,8 +54,11 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="key">Key</param> /// <param name="key">Key</param>
/// <returns>Parameter value</returns> /// <returns>Parameter value</returns>
T Get<T>(string key); T Get<T>(string key);
T GetOrDefault<T>(string key); T GetOrDefault<T>(string key);
T GetOrDefault<T>(string key, T defaultValue); T GetOrDefault<T>(string key, T defaultValue);
/// <summary> /// <summary>
/// Get parameter value by key /// Get parameter value by key
/// </summary> /// </summary>
@ -57,12 +66,14 @@ namespace ZeroLevel.Patterns.DependencyInjection
/// <param name="key">Key</param> /// <param name="key">Key</param>
/// <returns>Parameter value</returns> /// <returns>Parameter value</returns>
object Get(Type type, string key); object Get(Type type, string key);
/// <summary> /// <summary>
/// Check for parameter existence by key /// Check for parameter existence by key
/// </summary> /// </summary>
/// <typeparam name="T">Parameter type</typeparam> /// <typeparam name="T">Parameter type</typeparam>
/// <param name="key">Key</param> /// <param name="key">Key</param>
bool Contains<T>(string key); bool Contains<T>(string key);
#endregion
#endregion IEverythingStorage
} }
} }

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save

Powered by TurnKey Linux.