Move to .net standart

pull/1/head
a.bozhenov 5 years ago
parent 530fdb07ad
commit 4d556fbe10

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key="apiport" value="8885" />
<add key="socketport" value="8884" />
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

@ -1,97 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ZeroLevel.Services.Web;
namespace ZeroLevel.Discovery
{
public abstract class BaseController : ApiController
{
#region Responce create helpers
public static HttpResponseMessage BadRequestAnswer(HttpRequestMessage request, string message)
{
return request.CreateSelfDestroyingResponse(HttpStatusCode.BadRequest,
message.Replace("\r", " ").Replace("\n", " "));
}
public static HttpResponseMessage BadRequestAnswer(HttpRequestMessage request, Exception ex)
{
return request.CreateSelfDestroyingResponse(HttpStatusCode.BadRequest,
ex.Message.Replace("\r", " ").Replace("\n", " "));
}
public static HttpResponseMessage SuccessAnswer(HttpRequestMessage request)
{
return request.CreateSelfDestroyingResponse(HttpStatusCode.OK);
}
public static HttpResponseMessage NotFoundAnswer(HttpRequestMessage request, string message)
{
return request.CreateSelfDestroyingResponse(HttpStatusCode.Conflict,
message.Replace("\r", " ").Replace("\n", " "));
}
public static HttpResponseMessage HttpActionResult<T>(HttpRequestMessage request, Func<T> responseBuilder)
{
try
{
return request.CreateSelfDestroyingResponse(responseBuilder(), HttpStatusCode.OK);
}
catch (KeyNotFoundException knfEx)
{
return NotFoundAnswer(request, knfEx.Message);
}
catch (Exception ex)
{
Log.Error(ex, "Request {0} fault", request.RequestUri.PathAndQuery);
return BadRequestAnswer(request, ex);
}
}
protected static DateTime? ParseDateTime(string line)
{
var dateParts = line.Split('.', '/', '\\', '-').Select(p => p.Trim()).ToArray();
if (dateParts.Last().Length == 4)
{
dateParts = dateParts.Reverse().ToArray();
}
if (dateParts.First().Length != 4) return null;
int year, month = 1, day = 1;
if (false == int.TryParse(dateParts.First(), out year))
{
return null;
}
if (dateParts.Count() > 1)
{
if (false == int.TryParse(dateParts[1], out month))
{
return null;
}
}
if (dateParts.Count() > 2)
{
if (false == int.TryParse(dateParts[2], out day))
{
return null;
}
}
return new DateTime(year, month, day);
}
protected static String GetParameter(HttpRequestMessage request, string name)
{
var keys = UrlUtility.ParseQueryString(request.RequestUri.Query);
if (keys.ContainsKey(name))
{
return keys[name];
}
return null;
}
#endregion Responce create helpers
}
}

@ -1,72 +0,0 @@
using System.Net;
using System.Net.Http;
namespace ZeroLevel.Discovery
{
public static class HttpRequestMessagesExtensions
{
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
private const string OwinContext = "MS_OwinContext";
public static string GetClientIpAddress(HttpRequestMessage request)
{
//Web-hosting
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
//Self-hosting
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
//Owin-hosting
if (request.Properties.ContainsKey(OwinContext))
{
dynamic ctx = request.Properties[OwinContext];
if (ctx != null)
{
return ctx.Request.RemoteIpAddress;
}
}
return null;
}
public static HttpResponseMessage CreateSelfDestroyingResponse(this HttpRequestMessage request, HttpStatusCode code = HttpStatusCode.OK)
{
var response = request.CreateResponse(code);
request.RegisterForDispose(response);
return response;
}
public static HttpResponseMessage CreateSelfDestroyingResponse<T>(this HttpRequestMessage request, T val, HttpStatusCode code = HttpStatusCode.OK)
{
var response = request.CreateResponse<T>(code, val);
request.RegisterForDispose(response);
return response;
}
public static HttpResponseMessage CreateSelfDestroyingResponse(this HttpRequestMessage request, HttpStatusCode code, string reasonPhrase)
{
var response = request.CreateResponse(code);
response.ReasonPhrase = reasonPhrase;
request.RegisterForDispose(response);
return response;
}
public static HttpResponseMessage CreateSelfDestroyingResponse(this HttpRequestMessage request, HttpResponseMessage response)
{
request.RegisterForDispose(response);
return response;
}
}
}

@ -1,37 +0,0 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using ZeroLevel.Models;
using ZeroLevel.Network;
namespace ZeroLevel.Discovery
{
public class RoutesController :
BaseController
{
[HttpGet]
[Route("favicon.ico")]
public HttpResponseMessage favicon(HttpRequestMessage request)
{
return null;
}
[HttpGet]
[Route("api/v0/routes")]
[ResponseType(typeof(IEnumerable<ServiceEndpointsInfo>))]
public HttpResponseMessage GetRoutes(HttpRequestMessage request)
{
try
{
return request.CreateSelfDestroyingResponse(Injector.Default.Resolve<RouteTable>().Get());
}
catch (Exception ex)
{
Log.Error(ex, "Error with read records");
return BadRequestAnswer(request, ex);
}
}
}
}

@ -1,52 +0,0 @@
using System.Collections.Generic;
using ZeroLevel.Models;
using ZeroLevel.Network;
using ZeroLevel.Services.Applications;
using ZeroLevel.Services.Serialization;
namespace ZeroLevel.Discovery
{
public sealed class DiscoveryService
: BaseWindowsService, IZeroService
{
private IExService _exInbox;
public DiscoveryService()
: base("Discovery")
{
}
public override void DisposeResources()
{
}
public override void PauseAction()
{
}
public override void ResumeAction()
{
}
public override void StartAction()
{
var routeTable = new RouteTable();
Injector.Default.Register<RouteTable>(routeTable);
var port = Configuration.Default.First<int>("apiport");
Startup.StartWebPanel(port, false);
var socketPort = Configuration.Default.First<int>("socketport");
_exInbox = ExchangeTransportFactory.GetServer(socketPort);
_exInbox.RegisterInbox<IEnumerable<ServiceEndpointsInfo>>("services", (_, __) => routeTable.Get());
_exInbox.RegisterInbox<ExServiceInfo, InvokeResult>("register", (info, _, client) => routeTable.Append(info, client));
Log.Info($"TCP server started {_exInbox.Endpoint.Address}:{socketPort}");
}
public override void StopAction()
{
_exInbox.Dispose();
}
}
}

@ -1,11 +0,0 @@
namespace ZeroLevel.Discovery
{
internal class Program
{
private static void Main(string[] args)
{
Log.AddConsoleLogger(Services.Logging.LogLevel.System | Services.Logging.LogLevel.FullDebug);
Bootstrap.Startup<DiscoveryService>(args);
}
}
}

@ -1,35 +0,0 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ZeroLevel.Discovery")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ZeroLevel.Discovery")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4f55b23f-938c-4da2-b6dc-b6bc66d36073")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -1,222 +0,0 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using ZeroLevel.Models;
using ZeroLevel.Network;
namespace ZeroLevel.Discovery
{
public class RouteTable
: IDisposable
{
private readonly Dictionary<string, ServiceEndpointsInfo> _table = new Dictionary<string, ServiceEndpointsInfo>();
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
public RouteTable()
{
Load();
Sheduller.RemindEvery(TimeSpan.FromSeconds(10), Heartbeat);
}
#region Snapshot
private static readonly object _snapshot_lock = new object();
private void Save()
{
string snapshot;
_lock.EnterReadLock();
try
{
snapshot = JsonConvert.SerializeObject(_table);
}
catch (Exception ex)
{
Log.Error(ex, "Fault make snapshot");
return;
}
finally
{
_lock.ExitReadLock();
}
try
{
var snapshot_path = Path.Combine(Configuration.BaseDirectory, "snapshot.snp");
lock (_snapshot_lock)
{
File.WriteAllText(snapshot_path, snapshot);
}
}
catch (Exception ex)
{
Log.Error(ex, "Fault save shapshot");
}
}
private void Load()
{
try
{
var path = Path.Combine(Configuration.BaseDirectory, "snapshot.snp");
if (File.Exists(path))
{
var snapshot = File.ReadAllText(path);
if (string.IsNullOrWhiteSpace(snapshot) == false)
{
var restored = JsonConvert.DeserializeObject<Dictionary<string, ServiceEndpointsInfo>>(snapshot);
_lock.EnterWriteLock();
try
{
_table.Clear();
foreach (var r in restored)
{
_table.Add(r.Key, r.Value);
}
}
finally
{
_lock.ExitWriteLock();
}
}
}
}
catch (Exception ex)
{
Log.Error(ex, "Fault load snapshot");
}
}
#endregion Snapshot
private void Heartbeat(long taskid)
{
try
{
var removeEntities = new Dictionary<string, List<string>>();
_lock.EnterReadLock();
try
{
foreach (var pair in _table)
{
var endpointsToRemove = new List<string>();
foreach (var e in pair.Value.Endpoints)
{
if (NetUtils.TestConnection(NetUtils.CreateIPEndPoint(e)) == false)
{
if (false == removeEntities.ContainsKey(pair.Key))
{
removeEntities.Add(pair.Key, new List<string>());
}
removeEntities[pair.Key].Add(e);
}
}
}
}
finally
{
_lock.ExitReadLock();
}
_lock.EnterWriteLock();
try
{
foreach (var pair in removeEntities)
{
foreach (var ep in pair.Value)
{
_table[pair.Key].Endpoints.Remove(ep);
}
}
var badKeys = _table.Where(f => f.Value.Endpoints.Count == 0)
.Select(pair => pair.Key)
.ToList();
foreach (var badKey in badKeys)
{
_table.Remove(badKey);
}
}
finally
{
_lock.ExitWriteLock();
}
}
catch (Exception ex)
{
Log.Error(ex, "Fault heartbeat");
}
Save();
}
public InvokeResult Append(ExServiceInfo serviceInfo, IZBackward client)
{
InvokeResult result = null;
var endpoint = $"{client.Endpoint.Address}:{serviceInfo.Port}";
Log.Info($"Regiter request from {endpoint}. Service {serviceInfo?.ServiceKey}");
if (NetUtils.TestConnection(NetUtils.CreateIPEndPoint(endpoint)))
{
var key = $"{serviceInfo.ServiceGroup}:{serviceInfo.ServiceType}:{serviceInfo.ServiceKey.Trim().ToLowerInvariant()}";
_lock.EnterWriteLock();
try
{
if (false == _table.ContainsKey(key))
{
_table.Add(key, new ServiceEndpointsInfo
{
ServiceKey = serviceInfo.ServiceKey,
Version = serviceInfo.Version,
ServiceGroup = serviceInfo.ServiceGroup,
ServiceType = serviceInfo.ServiceType,
Endpoints = new List<string>()
});
_table[key].Endpoints.Add(endpoint);
Log.Info($"The service '{serviceInfo.ServiceKey}' registered on endpoint: {endpoint}");
}
else
{
var exists = _table[key];
if (exists.Endpoints.Contains(endpoint) == false)
{
Log.Info($"The service '{serviceInfo.ServiceKey}' register endpoint: {endpoint}");
exists.Endpoints.Add(endpoint);
}
}
}
catch (Exception ex)
{
Log.Error(ex, $"Fault append service ({serviceInfo.ServiceKey} {serviceInfo.Version}) endpoint '{endpoint}'");
result = InvokeResult.Fault(ex.Message);
}
finally
{
_lock.ExitWriteLock();
}
Save();
result = InvokeResult.Succeeding();
}
else
{
result = InvokeResult.Fault($"Appending endpoint '{endpoint}' canceled for service {serviceInfo.ServiceKey} ({serviceInfo.Version}) because endpoind no avaliable");
}
return result;
}
public IEnumerable<ServiceEndpointsInfo> Get()
{
_lock.EnterReadLock();
try
{
return _table.Values.ToList();
}
finally
{
_lock.ExitReadLock();
}
}
public void Dispose()
{
_lock.Dispose();
}
}
}

@ -1,80 +0,0 @@
using Microsoft.Owin.Hosting;
using Owin;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Routing;
namespace ZeroLevel.Discovery
{
public class LogRequestAndResponseHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// log request body
string requestBody = await request.Content.ReadAsStringAsync();
Log.Debug(requestBody);
// let other handlers process the request
var result = await base.SendAsync(request, cancellationToken);
if (result.Content != null)
{
//(result.Content as ObjectContent).Formatter.MediaTypeMappings.Clear();
// once response body is ready, log it
var responseBody = await result.Content.ReadAsStringAsync();
Log.Debug(responseBody);
}
return result;
}
}
public class EnableInheritRoutingDirectRouteProvider : DefaultDirectRouteProvider
{
protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
{
// inherit route attributes decorated on base class controller's actions
return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true);
}
}
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes(new EnableInheritRoutingDirectRouteProvider());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnsureInitialized();
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.Add(config.Formatters.JsonFormatter);
//if (_log_request_response)
{
config.MessageHandlers.Add(new LogRequestAndResponseHandler());
}
appBuilder.UseWebApi(config);
}
private static bool _log_request_response;
public static void StartWebPanel(int port,
bool log_request_response)
{
_log_request_response = log_request_response;
string baseAddress = string.Format("http://*:{0}/", port);
WebApp.Start<Startup>(url: baseAddress);
Log.Info(string.Format("Web panel url: {0}", baseAddress));
}
}
}

@ -1,96 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ZeroLevel.Discovery</RootNamespace>
<AssemblyName>ZeroLevel.Discovery</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Owin, Version=4.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.4.0.1\lib\net45\Microsoft.Owin.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin.Host.HttpListener, Version=4.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.Host.HttpListener.4.0.1\lib\net45\Microsoft.Owin.Host.HttpListener.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin.Hosting, Version=4.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.Hosting.4.0.1\lib\net45\Microsoft.Owin.Hosting.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL">
<HintPath>..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.7\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Web.Http, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.7\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.Owin, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Owin.5.2.7\lib\net45\System.Web.Http.Owin.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.SelfHost, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.SelfHost.5.2.7\lib\net45\System.Web.Http.SelfHost.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Controllers\BaseController.cs" />
<Compile Include="Controllers\HttpRequestMessagesExtensions.cs" />
<Compile Include="Controllers\RoutesController.cs" />
<Compile Include="DiscoveryService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RouteTable.cs" />
<Compile Include="Startup.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ZeroLevel\ZeroLevel.csproj">
<Project>{37020d8d-34e8-4ec3-a447-8396d5080457}</Project>
<Name>ZeroLevel</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.7" targetFramework="net472" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.7" targetFramework="net472" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.7" targetFramework="net472" />
<package id="Microsoft.AspNet.WebApi.SelfHost" version="5.2.7" targetFramework="net472" />
<package id="Microsoft.Owin" version="4.0.1" targetFramework="net472" />
<package id="Microsoft.Owin.Host.HttpListener" version="4.0.1" targetFramework="net472" />
<package id="Microsoft.Owin.Hosting" version="4.0.1" targetFramework="net472" />
<package id="Newtonsoft.Json" version="12.0.1" targetFramework="net472" />
<package id="Owin" version="1.0" targetFramework="net472" />
</packages>

@ -1,10 +1,9 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System;
using Xunit;
using ZeroLevel;
namespace ZeroArrayExtensionsTest
{
[TestClass]
public class ArrayExtensionsTest
{
internal class EQDTO
@ -30,7 +29,7 @@ namespace ZeroArrayExtensionsTest
}
}
[TestMethod]
[Fact]
public void ByteArrayEqualTest()
{
// Arrange
@ -44,20 +43,20 @@ namespace ZeroArrayExtensionsTest
var a8 = new byte[0];
// Assert
Assert.IsTrue(ArrayExtensions.UnsafeEquals(a1, a2));
Assert.IsTrue(ArrayExtensions.UnsafeEquals(a5, a6));
Assert.IsTrue(ArrayExtensions.UnsafeEquals(a7, a8));
Assert.True(ArrayExtensions.UnsafeEquals(a1, a2));
Assert.True(ArrayExtensions.UnsafeEquals(a5, a6));
Assert.True(ArrayExtensions.UnsafeEquals(a7, a8));
Assert.IsFalse(ArrayExtensions.UnsafeEquals(a1, a3));
Assert.IsFalse(ArrayExtensions.UnsafeEquals(a1, a4));
Assert.False(ArrayExtensions.UnsafeEquals(a1, a3));
Assert.False(ArrayExtensions.UnsafeEquals(a1, a4));
Assert.IsFalse(ArrayExtensions.UnsafeEquals(a1, a5));
Assert.IsFalse(ArrayExtensions.UnsafeEquals(a1, a7));
Assert.False(ArrayExtensions.UnsafeEquals(a1, a5));
Assert.False(ArrayExtensions.UnsafeEquals(a1, a7));
Assert.IsFalse(ArrayExtensions.UnsafeEquals(a5, a7));
Assert.False(ArrayExtensions.UnsafeEquals(a5, a7));
}
[TestMethod]
[Fact]
public void ArrayEqualTest()
{
// Arrange
@ -83,8 +82,8 @@ namespace ZeroArrayExtensionsTest
};
//Assert
Assert.IsTrue(ArrayExtensions.Contains(arr1, arr2));
Assert.IsFalse(ArrayExtensions.Contains(arr1, arr3));
Assert.True(ArrayExtensions.Contains(arr1, arr2));
Assert.False(ArrayExtensions.Contains(arr1, arr3));
}
}
}

@ -1,16 +1,12 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Linq;
using Xunit;
using ZeroLevel.Services.Collections;
using ZeroLevel.Services.ObjectMapping;
using ZeroLevel.Services.Reflection;
namespace ZeroLevel.CollectionUnitTests
{
[TestClass]
public class CollectionsTests
{
[TestMethod]
[Fact]
public void RoundRobinCollectionTest()
{
// Arrange
@ -26,24 +22,24 @@ namespace ZeroLevel.CollectionUnitTests
collection.Add(2);
collection.Add(3);
// Assert
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter1));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter1));
Assert.IsTrue(collection.MoveNext());
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter2));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter2));
Assert.IsTrue(collection.MoveNext());
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter3));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter3));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter1));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter1));
Assert.True(collection.MoveNext());
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter2));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter2));
Assert.True(collection.MoveNext());
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter3));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter3));
collection.Remove(2);
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter11));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter11));
Assert.IsTrue(collection.MoveNext());
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter12));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter12));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter11));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter11));
Assert.True(collection.MoveNext());
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter12));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GetCurrentSeq().ToArray(), iter12));
}
[TestMethod]
[Fact]
public void RoundRobinOverCollectionTest()
{
var arr = new int[] { 1, 2, 3 };
@ -54,54 +50,15 @@ namespace ZeroLevel.CollectionUnitTests
var iter3 = new int[] { 3, 1, 2 };
// Act
// Assert
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter1));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter2));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter3));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter1));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter2));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter3));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter1));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter2));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter3));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter1));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter2));
Assert.True(CollectionComparsionExtensions.OrderingEquals(collection.GenerateSeq().ToArray(), iter3));
}
[TestMethod]
public void EverythingStorageTest()
{
// Arrange
var storage = EverythingStorage.Create();
var date = DateTime.Now;
var typeBuilder = new DTOTypeBuilder("MyType");
typeBuilder.AppendField<string>("Title");
typeBuilder.AppendProperty<long>("Id");
typeBuilder.AppendProperty<DateTime>("Created");
var type = typeBuilder.Complete();
var mapper = TypeMapper.Create(type);
var instance = TypeHelpers.CreateNonInitializedInstance(type);
mapper.Set(instance, "Title", "This is title");
mapper.Set(instance, "Id", 1001001);
mapper.Set(instance, "Created", date);
// Act
storage.Add<string>("id", "stringidentity");
storage.Add<long>("id", 123);
storage.Add<int>("id", 234);
storage.Add(type, "rt", instance);
// Assert
Assert.IsTrue(storage.ContainsKey<int>("id"));
Assert.IsTrue(storage.ContainsKey<long>("id"));
Assert.IsTrue(storage.ContainsKey<string>("id"));
Assert.IsTrue(storage.ContainsKey(type, "rt"));
Assert.IsFalse(storage.ContainsKey<int>("somekey"));
Assert.IsFalse(storage.ContainsKey<Guid>("somekey"));
Assert.AreEqual(mapper.Get(storage.Get(type, "rt"), "Id"), (long)1001001);
Assert.AreEqual(mapper.Get(storage.Get(type, "rt"), "Created"), date);
Assert.AreEqual(mapper.Get(storage.Get(type, "rt"), "Title"), "This is title");
Assert.AreEqual(storage.Get<long>("id"), (long)123);
Assert.AreEqual(storage.Get<int>("id"), 234);
Assert.AreEqual(storage.Get<string>("id"), "stringidentity");
}
[TestMethod]
[Fact]
public void FixSizeQueueTest()
{
// Arrange
@ -115,14 +72,14 @@ namespace ZeroLevel.CollectionUnitTests
fix.Push(5);
// Assert
Assert.IsTrue(fix.Count == 3);
Assert.IsTrue(fix.Contains(3));
Assert.IsTrue(fix.Contains(4));
Assert.IsTrue(fix.Contains(5));
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(fix.Dump().ToArray(), new long[] { 3, 4, 5 }));
Assert.IsTrue(fix.Take() == 3);
Assert.IsTrue(fix.Count == 2);
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(fix.Dump().ToArray(), new long[] { 4, 5 }));
Assert.True(fix.Count == 3);
Assert.True(fix.Contains(3));
Assert.True(fix.Contains(4));
Assert.True(fix.Contains(5));
Assert.True(CollectionComparsionExtensions.OrderingEquals(fix.Dump().ToArray(), new long[] { 3, 4, 5 }));
Assert.True(fix.Take() == 3);
Assert.True(fix.Count == 2);
Assert.True(CollectionComparsionExtensions.OrderingEquals(fix.Dump().ToArray(), new long[] { 4, 5 }));
}
}
}

@ -1,6 +1,6 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System;
using System.Linq;
using Xunit;
using ZeroLevel.DocumentObjectModel;
using ZeroLevel.Network;
using ZeroLevel.Services.Encryption;
@ -9,7 +9,6 @@ using ZeroLevel.UnitTests.Models;
namespace ZeroLevel.EncryptionUnitTests
{
[TestClass]
public class EncryptionTests
{
private static double CalculateDeviation(byte[] data)
@ -19,7 +18,7 @@ namespace ZeroLevel.EncryptionUnitTests
return Math.Sqrt(sumOfSquaresOfDifferences / data.Length);
}
[TestMethod]
[Fact]
public void FastObfuscatorTest()
{
// Arrange
@ -43,13 +42,13 @@ namespace ZeroLevel.EncryptionUnitTests
var clone = MessageSerializer.Deserialize<Document>(data);
// Assert
Assert.AreEqual(deviation, deobf_deviation);
Assert.AreNotEqual(deviation, obf_deviation);
Assert.IsTrue(obf_deviation >= deviation);
Assert.IsTrue(comparator(instance, clone));
Assert.Equal(deviation, deobf_deviation);
Assert.NotEqual(deviation, obf_deviation);
Assert.True(obf_deviation >= deviation);
Assert.True(comparator(instance, clone));
}
[TestMethod]
[Fact]
public void NetworkStreamDataObfuscatorTest()
{
// Arrange
@ -73,10 +72,10 @@ namespace ZeroLevel.EncryptionUnitTests
var clone = MessageSerializer.Deserialize<Document>(data);
// Assert
Assert.AreEqual(deviation, deobf_deviation);
Assert.AreNotEqual(deviation, obf_deviation);
Assert.IsTrue(obf_deviation >= deviation);
Assert.IsTrue(comparator(instance, clone));
Assert.Equal(deviation, deobf_deviation);
Assert.NotEqual(deviation, obf_deviation);
Assert.True(obf_deviation >= deviation);
Assert.True(comparator(instance, clone));
}
}
}

@ -1,19 +1,14 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using ZeroLevel.Network;
namespace ZeroLevel.NetworkUnitTests
{
[TestClass]
public class ExchangeTests
{
[TestMethod]
[Fact]
public void HandleMessageTest()
{
// Arrange
@ -41,8 +36,8 @@ namespace ZeroLevel.NetworkUnitTests
locker.WaitOne(1000);
// Assert
Assert.IsTrue(ir.Success);
Assert.IsTrue(info.Equals(received));
Assert.True(ir.Success);
Assert.True(info.Equals(received));
// Dispose
locker.Dispose();
@ -50,7 +45,7 @@ namespace ZeroLevel.NetworkUnitTests
server.Dispose();
}
[TestMethod]
[Fact]
public void RequestMessageTest()
{
// Arrange
@ -85,8 +80,8 @@ namespace ZeroLevel.NetworkUnitTests
locker.WaitOne(1000);
// Assert
Assert.IsTrue(ir.Success);
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(new[] { info1, info2 }, received, (a, b) => a.Equals(b)));
Assert.True(ir.Success);
Assert.True(CollectionComparsionExtensions.OrderingEquals(new[] { info1, info2 }, received, (a, b) => a.Equals(b)));
// Dispose
locker.Dispose();

@ -1,15 +1,14 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System;
using System.Reflection;
using Xunit;
using ZeroInvokingTest.Models;
using ZeroLevel.Services.Invokation;
namespace ZeroInvokingTest
{
[TestClass]
public class InvokingTest
{
[TestMethod]
[Fact]
public void InvokeTypeAllMethod()
{
// Arrange
@ -21,14 +20,14 @@ namespace ZeroInvokingTest
var identityGetDateTime = invoker.GetInvokerIdentity("GetDateTime", new Type[] { typeof(DateTime) });
var identityGetHelp = invoker.GetInvokerIdentity("GetHelp", null);
// Assert
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetString, new object[] { "hello" }), "hello");
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetString, new object[] { "hello" }), "hello");
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
var date = DateTime.Now;
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
}
[TestMethod]
[Fact]
public void InvokeTypeMethodByName()
{
// Arrange
@ -43,48 +42,31 @@ namespace ZeroInvokingTest
var identityGetDateTime = invoker.GetInvokerIdentity("GetDateTime", new Type[] { typeof(DateTime) });
var identityGetHelp = invoker.GetInvokerIdentity("GetHelp", null);
// Assert
try
{
var obj = invoker.Invoke(new FakeClass(), identityGetString, new object[] { "hello" });
Assert.Fail("An exception should have been thrown");
}
catch { }
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
var date = DateTime.Now;
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
}
[TestMethod]
[Fact]
public void InvokeTypeMethodByFilter()
{
// Arrange
var invoker = InvokeWrapper.Create();
// Act
invoker.Configure<FakeClass>(m => m.Name.Equals("GetHelp") || m.Name.Equals("GetNumber"));
invoker.Configure<FakeClass>(m => m.Name.Equals("GetHelp") || m.Name.Equals("GetNumber") || m.Name.Equals("GetDateTime"));
var identityGetString = invoker.GetInvokerIdentity("GetString", new Type[] { typeof(string) });
var identityGetNumber = invoker.GetInvokerIdentity("GetNumber", new Type[] { typeof(int) });
var identityGetDateTime = invoker.GetInvokerIdentity("GetDateTime", new Type[] { typeof(DateTime) });
var identityGetHelp = invoker.GetInvokerIdentity("GetHelp", null);
// Assert
try
{
var obj = invoker.Invoke(new FakeClass(), identityGetString, new object[] { "hello" });
Assert.Fail("An exception should have been thrown");
}
catch { }
try
{
var date = DateTime.Now;
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.Fail("An exception should have been thrown");
}
catch { }
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
}
[TestMethod]
[Fact]
public void InvokeByMethodsList()
{
// Arrange
@ -102,14 +84,14 @@ namespace ZeroInvokingTest
var identityGetDateTime = invoker.GetInvokerIdentity("GetDateTime", new Type[] { typeof(DateTime) });
var identityGetHelp = invoker.GetInvokerIdentity("GetHelp", null);
// Assert
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetString, new object[] { "hello" }), "hello");
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetString, new object[] { "hello" }), "hello");
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
var date = DateTime.Now;
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
}
[TestMethod]
[Fact]
public void InvokeByMethods()
{
// Arrange
@ -124,14 +106,14 @@ namespace ZeroInvokingTest
var identityGetDateTime = invoker.GetInvokerIdentity("GetDateTime", new Type[] { typeof(DateTime) });
var identityGetHelp = invoker.GetInvokerIdentity("GetHelp", null);
// Assert
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetString, new object[] { "hello" }), "hello");
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetString, new object[] { "hello" }), "hello");
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetNumber, new object[] { 100 }), 100);
var date = DateTime.Now;
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.AreEqual(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetDateTime, new object[] { date }), date);
Assert.Equal(invoker.Invoke(new FakeClass(), identityGetHelp), "help");
}
[TestMethod]
[Fact]
public void InvokeStaticByMethods()
{
// Arrange
@ -144,13 +126,13 @@ namespace ZeroInvokingTest
var identityGetNumber = invoker.GetInvokerIdentity("GetNumber", new Type[] { typeof(int) });
var identityGetDateTime = invoker.GetInvokerIdentity("GetDateTime", new Type[] { typeof(DateTime) });
// Assert
Assert.AreEqual(invoker.InvokeStatic(identityGetString, new object[] { "hello" }), "hello");
Assert.AreEqual(invoker.InvokeStatic(identityGetNumber, new object[] { 100 }), 100);
Assert.Equal(invoker.InvokeStatic(identityGetString, new object[] { "hello" }), "hello");
Assert.Equal(invoker.InvokeStatic(identityGetNumber, new object[] { 100 }), 100);
var date = DateTime.Now;
Assert.AreEqual(invoker.InvokeStatic(identityGetDateTime, new object[] { date }), date);
Assert.Equal(invoker.InvokeStatic(identityGetDateTime, new object[] { date }), date);
}
[TestMethod]
[Fact]
public void InvokeByDelegate()
{
// Arrange
@ -159,7 +141,7 @@ namespace ZeroInvokingTest
var func = new Func<string, bool>(str => str.Length > 0);
var name = invoker.Configure(func);
// Assert
Assert.IsTrue((bool)invoker.Invoke(func.Target, name, new object[] { "hello" }));
Assert.True((bool)invoker.Invoke(func.Target, name, new object[] { "hello" }));
}
}
}

@ -1,16 +1,15 @@
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ZeroLevel.Services.ObjectMapping;
using ZeroMappingTest.Models;
using System.Collections.Generic;
using BusinessApp.DatabaseTest.Model;
using Xunit;
namespace ZeroMappingTest
{
[TestClass]
public class MappingTest
{
[TestMethod]
[Fact]
public void TestAbstractClassGetInfo()
{
// Arrange
@ -19,24 +18,24 @@ namespace ZeroMappingTest
var list = new List<string>();
mapper.TraversalMembers(f => list.Add(f.Name));
// Assert
Assert.IsTrue(mapper.Exists("Id"));
Assert.IsTrue(mapper.Exists("Title"));
Assert.IsTrue(mapper.Exists("Description"));
Assert.True(mapper.Exists("Id"));
Assert.True(mapper.Exists("Title"));
Assert.True(mapper.Exists("Description"));
Assert.IsTrue(list.Contains("Id"));
Assert.IsTrue(list.Contains("Title"));
Assert.IsTrue(list.Contains("Description"));
Assert.True(list.Contains("Id"));
Assert.True(list.Contains("Title"));
Assert.True(list.Contains("Description"));
Assert.IsFalse(mapper.Exists("Version"));
Assert.IsFalse(mapper.Exists("Created"));
Assert.False(mapper.Exists("Version"));
Assert.False(mapper.Exists("Created"));
Assert.IsFalse(list.Contains("Version"));
Assert.IsFalse(list.Contains("Created"));
Assert.False(list.Contains("Version"));
Assert.False(list.Contains("Created"));
Assert.AreEqual(mapper.EntityType, typeof(BaseClass));
Assert.Equal(mapper.EntityType, typeof(BaseClass));
}
[TestMethod]
[Fact]
public void TestInheritedClassGetInfo()
{
// Arrange
@ -45,34 +44,34 @@ namespace ZeroMappingTest
var list = new List<string>();
mapper.TraversalMembers(f => list.Add(f.Name));
// Assert
Assert.IsTrue(mapper.Exists("Id"));
Assert.IsTrue(mapper.Exists("Title"));
Assert.IsTrue(mapper.Exists("Description"));
Assert.IsTrue(mapper.Exists("Number"));
Assert.IsTrue(mapper.Exists("Balance"));
Assert.IsTrue(mapper.Exists("ReadOnlyProperty"));
Assert.IsTrue(mapper.Exists("WriteOnlyProperty"));
Assert.IsTrue(list.Contains("Id"));
Assert.IsTrue(list.Contains("Title"));
Assert.IsTrue(list.Contains("Description"));
Assert.IsTrue(list.Contains("Number"));
Assert.IsTrue(list.Contains("Balance"));
Assert.IsTrue(list.Contains("ReadOnlyProperty"));
Assert.IsTrue(list.Contains("WriteOnlyProperty"));
Assert.IsFalse(mapper.Exists("HiddenField"));
Assert.IsFalse(mapper.Exists("Version"));
Assert.IsFalse(mapper.Exists("Created"));
Assert.IsFalse(list.Contains("HiddenField"));
Assert.IsFalse(list.Contains("Version"));
Assert.IsFalse(list.Contains("Created"));
Assert.AreEqual(mapper.EntityType, typeof(ChildClass));
}
[TestMethod]
Assert.True(mapper.Exists("Id"));
Assert.True(mapper.Exists("Title"));
Assert.True(mapper.Exists("Description"));
Assert.True(mapper.Exists("Number"));
Assert.True(mapper.Exists("Balance"));
Assert.True(mapper.Exists("ReadOnlyProperty"));
Assert.True(mapper.Exists("WriteOnlyProperty"));
Assert.True(list.Contains("Id"));
Assert.True(list.Contains("Title"));
Assert.True(list.Contains("Description"));
Assert.True(list.Contains("Number"));
Assert.True(list.Contains("Balance"));
Assert.True(list.Contains("ReadOnlyProperty"));
Assert.True(list.Contains("WriteOnlyProperty"));
Assert.False(mapper.Exists("HiddenField"));
Assert.False(mapper.Exists("Version"));
Assert.False(mapper.Exists("Created"));
Assert.False(list.Contains("HiddenField"));
Assert.False(list.Contains("Version"));
Assert.False(list.Contains("Created"));
Assert.Equal(mapper.EntityType, typeof(ChildClass));
}
[Fact]
public void TestAbstractClassMapping()
{
// Arrange
@ -94,24 +93,25 @@ namespace ZeroMappingTest
mapper.Set(instance, "Title", title);
mapper.Set(instance, "Description", description);
// Assert
Assert.AreEqual<Guid>(mapper.Get<Guid>(instance, "Id"), id);
Assert.AreEqual<string>(mapper.Get<string>(instance, "Title"), title);
Assert.AreEqual<string>(mapper.Get<string>(instance, "Description"), description);
Assert.Equal<Guid>(mapper.Get<Guid>(instance, "Id"), id);
Assert.Equal<string>(mapper.Get<string>(instance, "Title"), title);
Assert.Equal<string>(mapper.Get<string>(instance, "Description"), description);
Assert.Equal(mapper.Get(instance, "Id"), id);
Assert.Equal(mapper.Get(instance, "Title"), title);
Assert.Equal(mapper.Get(instance, "Description"), description);
Assert.AreEqual(mapper.Get(instance, "Id"), id);
Assert.AreEqual(mapper.Get(instance, "Title"), title);
Assert.AreEqual(mapper.Get(instance, "Description"), description);
try
{
mapper.Get(instance, "Number");
Assert.Fail("Must be inaccessability");
Assert.True(false, "Must be inaccessability");
}
catch
{
}
}
[TestMethod]
[Fact]
public void TestInheritedClassMapping()
{
// Arrange
@ -139,23 +139,23 @@ namespace ZeroMappingTest
mapper.Set(instance, "Number", number);
mapper.Set(instance, "Balance", balance);
// Assert
Assert.AreEqual<Guid>(mapper.Get<Guid>(instance, "Id"), id);
Assert.AreEqual<string>(mapper.Get<string>(instance, "Title"), title);
Assert.AreEqual<string>(mapper.Get<string>(instance, "Description"), description);
Assert.AreEqual<int>(mapper.Get<int>(instance, "Number"), number);
Assert.AreEqual<int>(mapper.Get<int>(instance, "Balance"), balance);
Assert.AreEqual(mapper.Get(instance, "Id"), id);
Assert.AreEqual(mapper.Get(instance, "Title"), title);
Assert.AreEqual(mapper.Get(instance, "Description"), description);
Assert.AreEqual(mapper.Get(instance, "Number"), number);
Assert.AreEqual(mapper.Get(instance, "Balance"), balance);
Assert.Equal<Guid>(mapper.Get<Guid>(instance, "Id"), id);
Assert.Equal<string>(mapper.Get<string>(instance, "Title"), title);
Assert.Equal<string>(mapper.Get<string>(instance, "Description"), description);
Assert.Equal<int>(mapper.Get<int>(instance, "Number"), number);
Assert.Equal<int>(mapper.Get<int>(instance, "Balance"), balance);
Assert.Equal(mapper.Get(instance, "Id"), id);
Assert.Equal(mapper.Get(instance, "Title"), title);
Assert.Equal(mapper.Get(instance, "Description"), description);
Assert.Equal(mapper.Get(instance, "Number"), number);
Assert.Equal(mapper.Get(instance, "Balance"), balance);
try
{
var test = 1000;
mapper.Set(instance, "ReadOnlyProperty", test);
Assert.Fail("There should be no possibility to set a value.");
Assert.True(false, "There should be no possibility to set a value.");
}
catch
{
@ -165,7 +165,7 @@ namespace ZeroMappingTest
try
{
mapper.Get(instance, "WriteOnlyProperty");
Assert.Fail("There should be no possibility to get a value.");
Assert.True(false, "There should be no possibility to get a value.");
}
catch
{
@ -178,7 +178,7 @@ namespace ZeroMappingTest
}
catch
{
Assert.Fail("It should be possible to get the default value.");
Assert.True(false, "It should be possible to get the default value.");
}
try
@ -187,11 +187,11 @@ namespace ZeroMappingTest
}
catch(Exception ex)
{
Assert.Fail(ex.Message);
Assert.True(false, ex.Message);
}
}
[TestMethod]
[Fact]
public void TestMapperscaching()
{
// Arrange
@ -200,12 +200,12 @@ namespace ZeroMappingTest
var mapper3 = TypeMapper.Create<ChildClass>(false);
// Act
// Assert
Assert.AreSame(mapper1, mapper2);
Assert.AreNotSame(mapper1, mapper3);
Assert.AreNotSame(mapper3, mapper2);
Assert.Same(mapper1, mapper2);
Assert.NotSame(mapper1, mapper3);
Assert.NotSame(mapper3, mapper2);
}
[TestMethod]
[Fact]
public void PocoFieldMapper()
{
// Arrange
@ -214,21 +214,21 @@ namespace ZeroMappingTest
var obj = new PocoFields { Id = 1000, Date = date, Title = "Caption" };
// Assert
Assert.AreEqual(mapper.EntityType, typeof(PocoFields));
Assert.Equal(mapper.EntityType, typeof(PocoFields));
Assert.IsTrue(mapper.Exists("Id"));
Assert.IsTrue(mapper.Exists("Date"));
Assert.IsTrue(mapper.Exists("Title"));
Assert.True(mapper.Exists("Id"));
Assert.True(mapper.Exists("Date"));
Assert.True(mapper.Exists("Title"));
Assert.AreEqual(mapper.Get(obj, "Id"), (long)1000);
Assert.AreEqual(mapper.Get(obj, "Date"), date);
Assert.AreEqual(mapper.Get(obj, "Title"), "Caption");
Assert.Equal(mapper.Get(obj, "Id"), (long)1000);
Assert.Equal(mapper.Get(obj, "Date"), date);
Assert.Equal(mapper.Get(obj, "Title"), "Caption");
mapper.Set(obj, "Id", 1001);
Assert.AreEqual(mapper.Get(obj, "Id"), (long)1001);
Assert.Equal(mapper.Get(obj, "Id"), (long)1001);
}
[TestMethod]
[Fact]
public void PocoPropertiesMapper()
{
// Arrange
@ -237,18 +237,18 @@ namespace ZeroMappingTest
var obj = new PocoProperties { Id = 1000, Date = date, Title = "Caption" };
// Assert
Assert.AreEqual(mapper.EntityType, typeof(PocoProperties));
Assert.Equal(mapper.EntityType, typeof(PocoProperties));
Assert.IsTrue(mapper.Exists("Id"));
Assert.IsTrue(mapper.Exists("Date"));
Assert.IsTrue(mapper.Exists("Title"));
Assert.True(mapper.Exists("Id"));
Assert.True(mapper.Exists("Date"));
Assert.True(mapper.Exists("Title"));
Assert.AreEqual(mapper.Get(obj, "Id"), (long)1000);
Assert.AreEqual(mapper.Get(obj, "Date"), date);
Assert.AreEqual(mapper.Get(obj, "Title"), "Caption");
Assert.Equal(mapper.Get(obj, "Id"), (long)1000);
Assert.Equal(mapper.Get(obj, "Date"), date);
Assert.Equal(mapper.Get(obj, "Title"), "Caption");
mapper.Set(obj, "Id", 1001);
Assert.AreEqual(mapper.Get(obj, "Id"), (long)1001);
Assert.Equal(mapper.Get(obj, "Id"), (long)1001);
}
}
}

@ -1,13 +1,12 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System;
using Xunit;
using ZeroLevel.Specification;
namespace ZeroSpecificationPatternsTest
{
[TestClass]
public class PredicateBuilderTests
{
[TestMethod]
[Fact]
public void PredicateBuilder_FromExpression_AND()
{
// Arrange
@ -18,13 +17,13 @@ namespace ZeroSpecificationPatternsTest
And(str => char.IsLetter(str[0])).
And(str => char.IsUpper(str[0])).Compile();
// Assert
Assert.IsFalse(invoker("test"));
Assert.IsTrue(invoker("Test"));
Assert.IsFalse(invoker("1test"));
Assert.IsFalse(invoker("Test" + new string('_', 260)));
Assert.False(invoker("test"));
Assert.True(invoker("Test"));
Assert.False(invoker("1test"));
Assert.False(invoker("Test" + new string('_', 260)));
}
[TestMethod]
[Fact]
public void PredicateBuilder_FromFunc_AND()
{
// Arrange
@ -35,13 +34,13 @@ namespace ZeroSpecificationPatternsTest
And(str => Char.IsLetter(str[0])).
And(str => Char.IsUpper(str[0])).Compile();
// Assert
Assert.IsFalse(invoker("test"));
Assert.IsTrue(invoker("Test"));
Assert.IsFalse(invoker("1test"));
Assert.IsFalse(invoker("Test" + new string('_', 260)));
Assert.False(invoker("test"));
Assert.True(invoker("Test"));
Assert.False(invoker("1test"));
Assert.False(invoker("Test" + new string('_', 260)));
}
[TestMethod]
[Fact]
public void PredicateBuilder_FromExpression_OR()
{
// Arrange
@ -54,14 +53,14 @@ namespace ZeroSpecificationPatternsTest
Or(str => str.Equals("wow", StringComparison.OrdinalIgnoreCase)).
Compile();
// Assert
Assert.IsTrue(invoker("hello"));
Assert.IsTrue(invoker("world"));
Assert.IsTrue(invoker("test"));
Assert.IsTrue(invoker("wow"));
Assert.IsFalse(invoker("Tests"));
Assert.True(invoker("hello"));
Assert.True(invoker("world"));
Assert.True(invoker("test"));
Assert.True(invoker("wow"));
Assert.False(invoker("Tests"));
}
[TestMethod]
[Fact]
public void PredicateBuilder_FromFunc_OR()
{
// Arrange
@ -73,14 +72,14 @@ namespace ZeroSpecificationPatternsTest
Or(str => str.Equals("wow", StringComparison.OrdinalIgnoreCase)).
Compile();
// Assert
Assert.IsTrue(invoker("hello"));
Assert.IsTrue(invoker("world"));
Assert.IsTrue(invoker("test"));
Assert.IsTrue(invoker("wow"));
Assert.IsFalse(invoker("Tests"));
Assert.True(invoker("hello"));
Assert.True(invoker("world"));
Assert.True(invoker("test"));
Assert.True(invoker("wow"));
Assert.False(invoker("Tests"));
}
[TestMethod]
[Fact]
public void PredicateBuilder_FromExpression_NOT()
{
// Arrange
@ -90,13 +89,13 @@ namespace ZeroSpecificationPatternsTest
var invoker = expression.Not().
Compile();
// Assert
Assert.IsFalse(invoker(1));
Assert.IsFalse(invoker(50));
Assert.IsTrue(invoker(100));
Assert.IsTrue(invoker(0));
Assert.False(invoker(1));
Assert.False(invoker(50));
Assert.True(invoker(100));
Assert.True(invoker(0));
}
[TestMethod]
[Fact]
public void PredicateBuilder_FromFunc_NOT()
{
// Arrange
@ -105,10 +104,10 @@ namespace ZeroSpecificationPatternsTest
var invoker = expression.Not().
Compile();
// Assert
Assert.IsFalse(invoker(1));
Assert.IsFalse(invoker(50));
Assert.IsTrue(invoker(100));
Assert.IsTrue(invoker(0));
Assert.False(invoker(1));
Assert.False(invoker(50));
Assert.True(invoker(100));
Assert.True(invoker(0));
}
}
}

@ -1,20 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ZeroLevel.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ZeroLevel.UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("c500b489-c432-499d-b0e4-b41998b12c49")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -1,7 +1,7 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using ZeroLevel.Patterns.Queries;
using ZeroSpecificationPatternsTest.Models;
@ -10,7 +10,6 @@ namespace ZeroSpecificationPatternsTest
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class QueriesTests
{
private static bool TestDTOEqual(TestDTO left, TestDTO right)
@ -26,7 +25,7 @@ namespace ZeroSpecificationPatternsTest
return true;
}
[TestMethod]
[Fact]
public void MemoryStoragePostTest()
{
var storage = new MemoryStorage<TestDTO>();
@ -57,15 +56,15 @@ namespace ZeroSpecificationPatternsTest
Summary = "Summary #3",
Title = "Title #3"
});
Assert.IsTrue(a1.Success);
Assert.AreEqual<long>(a1.Count, 1);
Assert.IsTrue(a2.Success);
Assert.AreEqual<long>(a2.Count, 1);
Assert.IsTrue(a3.Success);
Assert.AreEqual<long>(a3.Count, 1);
Assert.True(a1.Success);
Assert.Equal<long>(a1.Count, 1);
Assert.True(a2.Success);
Assert.Equal<long>(a2.Count, 1);
Assert.True(a3.Success);
Assert.Equal<long>(a3.Count, 1);
}
[TestMethod]
[Fact]
public void MemoryStorageGetAllTest()
{
var set = new List<TestDTO>();
@ -100,13 +99,13 @@ namespace ZeroSpecificationPatternsTest
foreach (var i in set)
{
var ar = storage.Post(i);
Assert.IsTrue(ar.Success);
Assert.AreEqual<long>(ar.Count, 1);
Assert.True(ar.Success);
Assert.Equal<long>(ar.Count, 1);
}
// Test equals set and storage data
foreach (var i in storage.Get())
{
Assert.IsTrue(set.Exists(dto => TestDTOEqual(i, dto)));
Assert.True(set.Exists(dto => TestDTOEqual(i, dto)));
}
// Modify originals
foreach (var i in set)
@ -116,12 +115,12 @@ namespace ZeroSpecificationPatternsTest
// Test independences storage from original
foreach (var i in storage.Get())
{
Assert.IsFalse(set.Exists(dto => TestDTOEqual(i, dto)));
Assert.False(set.Exists(dto => TestDTOEqual(i, dto)));
}
}
[TestMethod]
[Fact]
public void MemoryStorageGetByTest()
{
var set = new List<TestDTO>();
@ -156,35 +155,35 @@ namespace ZeroSpecificationPatternsTest
foreach (var i in set)
{
var ar = storage.Post(i);
Assert.IsTrue(ar.Success);
Assert.AreEqual<long>(ar.Count, 1);
Assert.True(ar.Success);
Assert.Equal<long>(ar.Count, 1);
}
// Test equals set and storage data
foreach (var i in storage.Get())
{
Assert.IsTrue(set.Exists(dto => TestDTOEqual(i, dto)));
Assert.True(set.Exists(dto => TestDTOEqual(i, dto)));
}
foreach (var i in storage.Get(Query.ALL()))
{
Assert.IsTrue(set.Exists(dto => TestDTOEqual(i, dto)));
Assert.True(set.Exists(dto => TestDTOEqual(i, dto)));
}
var result_eq = storage.Get(Query.EQ("Title", "Title #1"));
Assert.AreEqual<int>(result_eq.Count(), 1);
Assert.IsTrue(TestDTOEqual(set[0], result_eq.First()));
Assert.Equal<int>(result_eq.Count(), 1);
Assert.True(TestDTOEqual(set[0], result_eq.First()));
var result_neq = storage.Get(Query.NEQ("Title", "Title #1"));
Assert.AreEqual<int>(result_neq.Count(), 2);
Assert.IsTrue(TestDTOEqual(set[1], result_neq.First()));
Assert.IsTrue(TestDTOEqual(set[2], result_neq.Skip(1).First()));
Assert.Equal<int>(result_neq.Count(), 2);
Assert.True(TestDTOEqual(set[1], result_neq.First()));
Assert.True(TestDTOEqual(set[2], result_neq.Skip(1).First()));
var result_gt = storage.Get(Query.GT("Number", 1));
Assert.AreEqual<int>(result_gt.Count(), 2);
Assert.IsTrue(TestDTOEqual(set[0], result_gt.First()));
Assert.IsTrue(TestDTOEqual(set[2], result_gt.Skip(1).First()));
Assert.Equal<int>(result_gt.Count(), 2);
Assert.True(TestDTOEqual(set[0], result_gt.First()));
Assert.True(TestDTOEqual(set[2], result_gt.Skip(1).First()));
var result_lt = storage.Get(Query.LT("Number", 1));
Assert.AreEqual<int>(result_lt.Count(), 1);
Assert.IsTrue(TestDTOEqual(set[1], result_lt.First()));
Assert.Equal<int>(result_lt.Count(), 1);
Assert.True(TestDTOEqual(set[1], result_lt.First()));
}
}
}

@ -1,39 +0,0 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using ZeroLevel.Services.ObjectMapping;
using ZeroLevel.Services.Reflection;
namespace ZeroLevel.ReflectionUnitTests
{
[TestClass]
public class ReflectionTests
{
[TestMethod]
public void TestDTORuntymeBuildedTypes()
{
// Arrange
var date = DateTime.Now;
var typeBuilder = new DTOTypeBuilder("MyType");
typeBuilder.AppendField<string>("Title");
typeBuilder.AppendProperty<long>("Id");
typeBuilder.AppendProperty<DateTime>("Created");
var type = typeBuilder.Complete();
// Act
var mapper = TypeMapper.Create(type);
var instance = TypeHelpers.CreateNonInitializedInstance(type);
mapper.Set(instance, "Title", "This is title");
mapper.Set(instance, "Id", 1001001);
mapper.Set(instance, "Created", date);
// Assert
Assert.IsTrue(mapper.Exists("Title"));
Assert.IsTrue(mapper.Exists("Id"));
Assert.IsTrue(mapper.Exists("Created"));
Assert.AreEqual(mapper.Get(instance, "Id"), (long)1001001);
Assert.AreEqual(mapper.Get(instance, "Created"), date);
Assert.AreEqual(mapper.Get(instance, "Title"), "This is title");
}
}
}

@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Net;
using DOM.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Xunit;
using ZeroLevel.DocumentObjectModel;
using ZeroLevel.Network;
using ZeroLevel.Services.Serialization;
@ -11,7 +11,6 @@ using ZeroLevel.UnitTests.Models;
namespace ZeroLevel.UnitTests
{
[TestClass]
public class SerializationTests
{
private static bool TestOrderingEquals<T>(IEnumerable<T> A, IEnumerable<T> B, Func<T, T, bool> comparer)
@ -38,11 +37,11 @@ namespace ZeroLevel.UnitTests
// Assert
if (comparator == null)
{
Assert.AreEqual<T>(value, clone);
Assert.Equal<T>(value, clone);
}
else
{
Assert.IsTrue(comparator(value, clone));
Assert.True(comparator(value, clone));
}
}
@ -56,15 +55,15 @@ namespace ZeroLevel.UnitTests
if (value == null && clone != null && !clone.Any()) return; // OK
if (comparator == null)
{
Assert.IsTrue(CollectionComparsionExtensions.OrderingEquals(value, clone));
Assert.True(CollectionComparsionExtensions.OrderingEquals(value, clone));
}
else
{
Assert.IsTrue(TestOrderingEquals(value, clone, comparator));
Assert.True(TestOrderingEquals(value, clone, comparator));
}
}
[TestMethod]
[Fact]
public void SerializeDateTime()
{
MakePrimitiveTest<DateTime>(DateTime.Now);
@ -75,7 +74,7 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<DateTime>(DateTime.MaxValue);
}
[TestMethod]
[Fact]
public void SerializeIPAddress()
{
var comparator = new Func<IPAddress, IPAddress, bool>((left, right) => NetUtils.Compare(left, right) == 0);
@ -89,7 +88,7 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<IPAddress>(IPAddress.Parse("93.111.16.58"), comparator);
}
[TestMethod]
[Fact]
public void SerializeIPEndPoint()
{
var comparator = new Func<IPEndPoint, IPEndPoint, bool>((left, right) => NetUtils.Compare(left, right) == 0);
@ -103,14 +102,14 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<IPEndPoint>(new IPEndPoint(IPAddress.Parse("93.111.16.58"), IPEndPoint.MinPort), comparator);
}
[TestMethod]
[Fact]
public void SerializeGuid()
{
MakePrimitiveTest<Guid>(Guid.Empty);
MakePrimitiveTest<Guid>(Guid.NewGuid());
}
[TestMethod]
[Fact]
public void SerializeTimeSpan()
{
MakePrimitiveTest<TimeSpan>(TimeSpan.MaxValue);
@ -122,7 +121,7 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<TimeSpan>(TimeSpan.FromTicks(0));
}
[TestMethod]
[Fact]
public void SerializeString()
{
var comparator = new Func<string, string, bool>((left, right) =>
@ -137,7 +136,7 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<String>("𐌼𐌰𐌲 𐌲𐌻𐌴𐍃 𐌹̈𐍄𐌰𐌽, 𐌽𐌹 𐌼𐌹𐍃 𐍅𐌿 𐌽𐌳𐌰𐌽 𐌱𐍂𐌹𐌲𐌲𐌹𐌸", comparator);
}
[TestMethod]
[Fact]
public void SerializeInt32()
{
MakePrimitiveTest<Int32>(-0);
@ -148,7 +147,7 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<Int32>(Int32.MaxValue);
}
[TestMethod]
[Fact]
public void SerializeInt64()
{
MakePrimitiveTest<Int64>(-0);
@ -161,7 +160,7 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<Int64>(Int64.MaxValue / 2);
}
[TestMethod]
[Fact]
public void SerializeDecimal()
{
MakePrimitiveTest<Decimal>(-0);
@ -174,7 +173,7 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<Decimal>(Decimal.MaxValue / 2);
}
[TestMethod]
[Fact]
public void SerializeFloat()
{
MakePrimitiveTest<float>(-0);
@ -187,7 +186,7 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<float>(float.MaxValue / 2);
}
[TestMethod]
[Fact]
public void SerializeDouble()
{
MakePrimitiveTest<Double>(-0);
@ -200,14 +199,14 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<Double>(Double.MaxValue / 2);
}
[TestMethod]
[Fact]
public void SerializeBoolean()
{
MakePrimitiveTest<Boolean>(true);
MakePrimitiveTest<Boolean>(false);
}
[TestMethod]
[Fact]
public void SerializeByte()
{
MakePrimitiveTest<Byte>(0);
@ -218,7 +217,7 @@ namespace ZeroLevel.UnitTests
MakePrimitiveTest<Byte>(255);
}
[TestMethod]
[Fact]
public void SerializeBytes()
{
var comparator = new Func<byte[], byte[], bool>((left, right) =>
@ -233,7 +232,7 @@ namespace ZeroLevel.UnitTests
COLLECTIONS
*/
[TestMethod]
[Fact]
public void SerializeCollectionDateTime()
{
MakeCollectionTest<DateTime>(null);
@ -241,7 +240,7 @@ namespace ZeroLevel.UnitTests
MakeCollectionTest<DateTime>(new DateTime[] { DateTime.Now, DateTime.UtcNow, DateTime.Today, DateTime.Now.AddYears(2000), DateTime.MinValue, DateTime.MaxValue });
}
[TestMethod]
[Fact]
public void SerializeCollectionIPAddress()
{
var comparator = new Func<IPAddress, IPAddress, bool>((left, right) => NetUtils.Compare(left, right) == 0);
@ -249,7 +248,7 @@ namespace ZeroLevel.UnitTests
MakeCollectionTest<IPAddress>(new IPAddress[] { IPAddress.Any, IPAddress.Broadcast, IPAddress.IPv6Any, IPAddress.IPv6Loopback, IPAddress.IPv6None, IPAddress.Loopback, IPAddress.None, IPAddress.Parse("93.111.16.58") }, comparator);
}
[TestMethod]
[Fact]
public void SerializeCollectionIPEndPoint()
{
var comparator = new Func<IPEndPoint, IPEndPoint, bool>((left, right) => NetUtils.Compare(left, right) == 0);
@ -258,7 +257,7 @@ namespace ZeroLevel.UnitTests
MakeCollectionTest<IPEndPoint>(new IPEndPoint[] { new IPEndPoint(IPAddress.Any, 1), new IPEndPoint(IPAddress.Broadcast, 600), new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MaxPort), new IPEndPoint(IPAddress.IPv6Loopback, 8080), new IPEndPoint(IPAddress.IPv6None, 80), new IPEndPoint(IPAddress.Loopback, 9000), new IPEndPoint(IPAddress.None, 0), new IPEndPoint(IPAddress.Parse("93.111.16.58"), IPEndPoint.MinPort) }, comparator);
}
[TestMethod]
[Fact]
public void SerializeCollectionGuid()
{
MakeCollectionTest<Guid>(null);
@ -266,13 +265,13 @@ namespace ZeroLevel.UnitTests
MakeCollectionTest<Guid>(new Guid[] { Guid.Empty, Guid.NewGuid() });
}
[TestMethod]
[Fact]
public void SerializeCollectionTimeSpan()
{
MakeCollectionTest<TimeSpan>(new TimeSpan[] { TimeSpan.MaxValue, TimeSpan.MinValue, TimeSpan.Zero, TimeSpan.FromDays(1024), TimeSpan.FromMilliseconds(1), TimeSpan.FromTicks(1), TimeSpan.FromTicks(0) });
}
[TestMethod]
[Fact]
public void SerializeCollectionString()
{
var comparator = new Func<string, string, bool>((left, right) =>
@ -284,49 +283,49 @@ namespace ZeroLevel.UnitTests
}
[TestMethod]
[Fact]
public void SerializeCollectionInt32()
{
MakeCollectionTest<Int32>(new int[] { -0, 0, -10, 10, Int32.MinValue, Int32.MaxValue });
}
[TestMethod]
[Fact]
public void SerializeCollectionInt64()
{
MakeCollectionTest<Int64>(new long[] { -0, 0, -10, 10, Int64.MinValue, Int64.MaxValue, Int64.MinValue / 2, Int64.MaxValue / 2 });
}
[TestMethod]
[Fact]
public void SerializeCollectionDecimal()
{
MakeCollectionTest<Decimal>(new Decimal[] { -0, 0, -10, 10, Decimal.MinValue, Decimal.MaxValue, Decimal.MinValue / 2, Decimal.MaxValue / 2 });
}
[TestMethod]
[Fact]
public void SerializeCollectionFloat()
{
MakeCollectionTest<float>(new float[] { -0, 0, -10, 10, float.MinValue, float.MaxValue, float.MinValue / 2, float.MaxValue / 2 });
}
[TestMethod]
[Fact]
public void SerializeCollectionDouble()
{
MakeCollectionTest<Double>(new Double[] { -0, 0, -10, 10, Double.MinValue, Double.MaxValue, Double.MinValue / 2, Double.MaxValue / 2 });
}
[TestMethod]
[Fact]
public void SerializeCollectionBoolean()
{
MakeCollectionTest<Boolean>(new Boolean[] { true, false, true });
}
[TestMethod]
[Fact]
public void SerializeCollectionByte()
{
MakeCollectionTest<Byte>(new byte[] { 0, 3, -0, 1, 10, 128, 255 });
}
[TestMethod]
[Fact]
public void SerializeCollectionBytes()
{
var comparator = new Func<byte[], byte[], bool>((left, right) =>
@ -335,7 +334,7 @@ namespace ZeroLevel.UnitTests
MakeCollectionTest<Byte[]>(new Byte[][] { null, new byte[] { }, new byte[] { 1 }, new byte[] { 0, 1, 10, 100, 128, 255 } }, comparator);
}
[TestMethod]
[Fact]
public void SerializeCompositeObject()
{
var comparator = new Func<Document, Document, bool>((left, right) =>

@ -1,4 +1,4 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Xunit;
using ZeroLevel.Specification;
using ZeroSpecificationPatternsTest.Models;
using ZeroSpecificationPatternsTest.Specifications;
@ -8,10 +8,9 @@ namespace ZeroSpecificationPatternsTest
/// <summary>
/// Summary description for SpecificationPatternTest
/// </summary>
[TestClass]
public class SpecificationPatternTest
{
[TestMethod]
[Fact]
public void SimpleSpecificationTest()
{
// Assert
@ -52,38 +51,38 @@ namespace ZeroSpecificationPatternsTest
var title_specification_empty = new TitleSpecification(string.Empty);
// Assert
Assert.IsTrue(flag_spec_true.IsSatisfiedBy(dto_one));
Assert.IsFalse(flag_spec_false.IsSatisfiedBy(dto_one));
Assert.IsTrue(flag_spec_false.IsSatisfiedBy(dto_two));
Assert.IsFalse(flag_spec_true.IsSatisfiedBy(dto_two));
Assert.IsTrue(long_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(long_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(long_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(long_specification_full.IsSatisfiedBy(dto_two));
Assert.IsTrue(number_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(number_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(number_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(number_specification_full.IsSatisfiedBy(dto_two));
Assert.IsTrue(real_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(real_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(real_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(real_specification_full.IsSatisfiedBy(dto_two));
Assert.IsTrue(summary_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(summary_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(summary_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(summary_specification_full.IsSatisfiedBy(dto_two));
Assert.IsTrue(title_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(title_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(title_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(title_specification_full.IsSatisfiedBy(dto_two));
Assert.True(flag_spec_true.IsSatisfiedBy(dto_one));
Assert.False(flag_spec_false.IsSatisfiedBy(dto_one));
Assert.True(flag_spec_false.IsSatisfiedBy(dto_two));
Assert.False(flag_spec_true.IsSatisfiedBy(dto_two));
Assert.True(long_specification_full.IsSatisfiedBy(dto_one));
Assert.False(long_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(long_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(long_specification_full.IsSatisfiedBy(dto_two));
Assert.True(number_specification_full.IsSatisfiedBy(dto_one));
Assert.False(number_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(number_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(number_specification_full.IsSatisfiedBy(dto_two));
Assert.True(real_specification_full.IsSatisfiedBy(dto_one));
Assert.False(real_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(real_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(real_specification_full.IsSatisfiedBy(dto_two));
Assert.True(summary_specification_full.IsSatisfiedBy(dto_one));
Assert.False(summary_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(summary_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(summary_specification_full.IsSatisfiedBy(dto_two));
Assert.True(title_specification_full.IsSatisfiedBy(dto_one));
Assert.False(title_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(title_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(title_specification_full.IsSatisfiedBy(dto_two));
}
[TestMethod]
[Fact]
public void NotSpecificationTest()
{
// Assert
@ -124,38 +123,38 @@ namespace ZeroSpecificationPatternsTest
var title_specification_empty = new TitleSpecification(string.Empty).Not();
// Assert
Assert.IsFalse(flag_spec_true.IsSatisfiedBy(dto_one));
Assert.IsTrue(flag_spec_false.IsSatisfiedBy(dto_one));
Assert.IsFalse(flag_spec_false.IsSatisfiedBy(dto_two));
Assert.IsTrue(flag_spec_true.IsSatisfiedBy(dto_two));
Assert.IsFalse(long_specification_full.IsSatisfiedBy(dto_one));
Assert.IsTrue(long_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsFalse(long_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsTrue(long_specification_full.IsSatisfiedBy(dto_two));
Assert.IsFalse(number_specification_full.IsSatisfiedBy(dto_one));
Assert.IsTrue(number_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsFalse(number_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsTrue(number_specification_full.IsSatisfiedBy(dto_two));
Assert.IsFalse(real_specification_full.IsSatisfiedBy(dto_one));
Assert.IsTrue(real_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsFalse(real_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsTrue(real_specification_full.IsSatisfiedBy(dto_two));
Assert.IsFalse(summary_specification_full.IsSatisfiedBy(dto_one));
Assert.IsTrue(summary_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsFalse(summary_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsTrue(summary_specification_full.IsSatisfiedBy(dto_two));
Assert.IsFalse(title_specification_full.IsSatisfiedBy(dto_one));
Assert.IsTrue(title_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsFalse(title_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsTrue(title_specification_full.IsSatisfiedBy(dto_two));
Assert.False(flag_spec_true.IsSatisfiedBy(dto_one));
Assert.True(flag_spec_false.IsSatisfiedBy(dto_one));
Assert.False(flag_spec_false.IsSatisfiedBy(dto_two));
Assert.True(flag_spec_true.IsSatisfiedBy(dto_two));
Assert.False(long_specification_full.IsSatisfiedBy(dto_one));
Assert.True(long_specification_empty.IsSatisfiedBy(dto_one));
Assert.False(long_specification_empty.IsSatisfiedBy(dto_two));
Assert.True(long_specification_full.IsSatisfiedBy(dto_two));
Assert.False(number_specification_full.IsSatisfiedBy(dto_one));
Assert.True(number_specification_empty.IsSatisfiedBy(dto_one));
Assert.False(number_specification_empty.IsSatisfiedBy(dto_two));
Assert.True(number_specification_full.IsSatisfiedBy(dto_two));
Assert.False(real_specification_full.IsSatisfiedBy(dto_one));
Assert.True(real_specification_empty.IsSatisfiedBy(dto_one));
Assert.False(real_specification_empty.IsSatisfiedBy(dto_two));
Assert.True(real_specification_full.IsSatisfiedBy(dto_two));
Assert.False(summary_specification_full.IsSatisfiedBy(dto_one));
Assert.True(summary_specification_empty.IsSatisfiedBy(dto_one));
Assert.False(summary_specification_empty.IsSatisfiedBy(dto_two));
Assert.True(summary_specification_full.IsSatisfiedBy(dto_two));
Assert.False(title_specification_full.IsSatisfiedBy(dto_one));
Assert.True(title_specification_empty.IsSatisfiedBy(dto_one));
Assert.False(title_specification_empty.IsSatisfiedBy(dto_two));
Assert.True(title_specification_full.IsSatisfiedBy(dto_two));
}
[TestMethod]
[Fact]
public void ComposedAndSpecificationTest()
{
// Assert
@ -212,13 +211,13 @@ namespace ZeroSpecificationPatternsTest
And(title_specification_empty);
// Assert
Assert.IsTrue(composed_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(composed_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(composed_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(composed_full.IsSatisfiedBy(dto_two));
Assert.True(composed_full.IsSatisfiedBy(dto_one));
Assert.False(composed_empty.IsSatisfiedBy(dto_one));
Assert.True(composed_empty.IsSatisfiedBy(dto_two));
Assert.False(composed_full.IsSatisfiedBy(dto_two));
}
[TestMethod]
[Fact]
public void ComposedOrSpecificationTest()
{
// Assert
@ -275,13 +274,13 @@ namespace ZeroSpecificationPatternsTest
Or(title_specification_empty);
// Assert
Assert.IsTrue(composed_full.IsSatisfiedBy(dto_one));
Assert.IsTrue(composed_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(composed_empty.IsSatisfiedBy(dto_two));
Assert.IsTrue(composed_full.IsSatisfiedBy(dto_two));
Assert.True(composed_full.IsSatisfiedBy(dto_one));
Assert.True(composed_empty.IsSatisfiedBy(dto_one));
Assert.True(composed_empty.IsSatisfiedBy(dto_two));
Assert.True(composed_full.IsSatisfiedBy(dto_two));
}
[TestMethod]
[Fact]
public void ExpressionSpecificationTest()
{
// Assert
@ -322,38 +321,38 @@ namespace ZeroSpecificationPatternsTest
var title_specification_empty = new ExpressionSpecification<TestDTO>(o => o.Title == string.Empty);
// Assert
Assert.IsTrue(flag_spec_true.IsSatisfiedBy(dto_one));
Assert.IsFalse(flag_spec_false.IsSatisfiedBy(dto_one));
Assert.IsTrue(flag_spec_false.IsSatisfiedBy(dto_two));
Assert.IsFalse(flag_spec_true.IsSatisfiedBy(dto_two));
Assert.IsTrue(long_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(long_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(long_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(long_specification_full.IsSatisfiedBy(dto_two));
Assert.IsTrue(number_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(number_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(number_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(number_specification_full.IsSatisfiedBy(dto_two));
Assert.IsTrue(real_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(real_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(real_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(real_specification_full.IsSatisfiedBy(dto_two));
Assert.IsTrue(summary_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(summary_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(summary_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(summary_specification_full.IsSatisfiedBy(dto_two));
Assert.IsTrue(title_specification_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(title_specification_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(title_specification_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(title_specification_full.IsSatisfiedBy(dto_two));
Assert.True(flag_spec_true.IsSatisfiedBy(dto_one));
Assert.False(flag_spec_false.IsSatisfiedBy(dto_one));
Assert.True(flag_spec_false.IsSatisfiedBy(dto_two));
Assert.False(flag_spec_true.IsSatisfiedBy(dto_two));
Assert.True(long_specification_full.IsSatisfiedBy(dto_one));
Assert.False(long_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(long_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(long_specification_full.IsSatisfiedBy(dto_two));
Assert.True(number_specification_full.IsSatisfiedBy(dto_one));
Assert.False(number_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(number_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(number_specification_full.IsSatisfiedBy(dto_two));
Assert.True(real_specification_full.IsSatisfiedBy(dto_one));
Assert.False(real_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(real_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(real_specification_full.IsSatisfiedBy(dto_two));
Assert.True(summary_specification_full.IsSatisfiedBy(dto_one));
Assert.False(summary_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(summary_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(summary_specification_full.IsSatisfiedBy(dto_two));
Assert.True(title_specification_full.IsSatisfiedBy(dto_one));
Assert.False(title_specification_empty.IsSatisfiedBy(dto_one));
Assert.True(title_specification_empty.IsSatisfiedBy(dto_two));
Assert.False(title_specification_full.IsSatisfiedBy(dto_two));
}
[TestMethod]
[Fact]
public void ComposedExpressionSpecificationTest()
{
// Assert
@ -410,10 +409,10 @@ namespace ZeroSpecificationPatternsTest
And(title_specification_empty);
// Assert
Assert.IsTrue(composed_full.IsSatisfiedBy(dto_one));
Assert.IsFalse(composed_empty.IsSatisfiedBy(dto_one));
Assert.IsTrue(composed_empty.IsSatisfiedBy(dto_two));
Assert.IsFalse(composed_full.IsSatisfiedBy(dto_two));
Assert.True(composed_full.IsSatisfiedBy(dto_one));
Assert.False(composed_empty.IsSatisfiedBy(dto_one));
Assert.True(composed_empty.IsSatisfiedBy(dto_two));
Assert.False(composed_full.IsSatisfiedBy(dto_two));
}
}
}

@ -1,99 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\MSTest.TestAdapter.1.3.2\build\net45\MSTest.TestAdapter.props" Condition="Exists('..\packages\MSTest.TestAdapter.1.3.2\build\net45\MSTest.TestAdapter.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C500B489-C432-499D-B0E4-B41998B12C49}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ZeroLevel.UnitTests</RootNamespace>
<AssemblyName>ZeroLevel.UnitTests</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFramework>netcoreapp2.2</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="ArrayToolsTest.cs" />
<Compile Include="CollectionsTests.cs" />
<Compile Include="EncryptionTests.cs" />
<Compile Include="ExchangeTests.cs" />
<Compile Include="InvokingTest.cs" />
<Compile Include="MappingTest.cs" />
<Compile Include="Models\BaseClass.cs" />
<Compile Include="Models\BaseFakeClass.cs" />
<Compile Include="Models\ChildClass.cs" />
<Compile Include="Models\CompositeInstanceFactory.cs" />
<Compile Include="Models\FakeClass.cs" />
<Compile Include="Models\PocoFields.cs" />
<Compile Include="Models\PocoProperties.cs" />
<Compile Include="Models\Specifications\IsFlagSpecification.cs" />
<Compile Include="Models\Specifications\LongNumberSpecification.cs" />
<Compile Include="Models\Specifications\NumberSpecification.cs" />
<Compile Include="Models\Specifications\RealSpecification.cs" />
<Compile Include="Models\Specifications\SummarySpecification.cs" />
<Compile Include="Models\Specifications\TitleSpecification.cs" />
<Compile Include="Models\StaticFakeClass.cs" />
<Compile Include="Models\TestDTO.cs" />
<Compile Include="PredicateBuilderTests.cs" />
<Compile Include="QueriesTests.cs" />
<Compile Include="ReflectionTests.cs" />
<Compile Include="SerializationTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SpecificationPatternTest.cs" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<ProjectReference Include="..\ZeroLevel\ZeroLevel.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ZeroLevel\ZeroLevel.csproj">
<Project>{37020d8d-34e8-4ec3-a447-8396d5080457}</Project>
<Name>ZeroLevel</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.3.2\build\net45\MSTest.TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.3.2\build\net45\MSTest.TestAdapter.props'))" />
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.3.2\build\net45\MSTest.TestAdapter.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.3.2\build\net45\MSTest.TestAdapter.targets'))" />
</Target>
<Import Project="..\packages\MSTest.TestAdapter.1.3.2\build\net45\MSTest.TestAdapter.targets" Condition="Exists('..\packages\MSTest.TestAdapter.1.3.2\build\net45\MSTest.TestAdapter.targets')" />
</Project>

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MSTest.TestAdapter" version="1.3.2" targetFramework="net472" />
<package id="MSTest.TestFramework" version="1.3.2" targetFramework="net472" />
</packages>

@ -3,63 +3,29 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.421
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZeroLevel", "ZeroLevel\ZeroLevel.csproj", "{37020D8D-34E8-4EC3-A447-8396D5080457}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZeroLevel", "ZeroLevel\ZeroLevel.csproj", "{06C9E60E-D449-41A7-9BF0-A829AAF5D214}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZeroLevel.Discovery", "ZeroLevel.Discovery\ZeroLevel.Discovery.csproj", "{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZeroLevel.UnitTests", "ZeroLevel.UnitTests\ZeroLevel.UnitTests.csproj", "{C500B489-C432-499D-B0E4-B41998B12C49}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZeroLevel.UnitTests", "ZeroLevel.UnitTests\ZeroLevel.UnitTests.csproj", "{E5595DE0-B177-4078-AD10-8D3135014838}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{37020D8D-34E8-4EC3-A447-8396D5080457}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Debug|Any CPU.Build.0 = Debug|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Debug|x64.ActiveCfg = Debug|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Debug|x64.Build.0 = Debug|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Debug|x86.ActiveCfg = Debug|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Debug|x86.Build.0 = Debug|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Release|Any CPU.ActiveCfg = Release|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Release|Any CPU.Build.0 = Release|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Release|x64.ActiveCfg = Release|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Release|x64.Build.0 = Release|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Release|x86.ActiveCfg = Release|Any CPU
{37020D8D-34E8-4EC3-A447-8396D5080457}.Release|x86.Build.0 = Release|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Debug|x64.ActiveCfg = Debug|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Debug|x64.Build.0 = Debug|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Debug|x86.ActiveCfg = Debug|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Debug|x86.Build.0 = Debug|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Release|Any CPU.Build.0 = Release|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Release|x64.ActiveCfg = Release|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Release|x64.Build.0 = Release|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Release|x86.ActiveCfg = Release|Any CPU
{4F55B23F-938C-4DA2-B6DC-B6BC66D36073}.Release|x86.Build.0 = Release|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Debug|x64.ActiveCfg = Debug|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Debug|x64.Build.0 = Debug|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Debug|x86.ActiveCfg = Debug|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Debug|x86.Build.0 = Debug|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Release|Any CPU.Build.0 = Release|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Release|x64.ActiveCfg = Release|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Release|x64.Build.0 = Release|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Release|x86.ActiveCfg = Release|Any CPU
{C500B489-C432-499D-B0E4-B41998B12C49}.Release|x86.Build.0 = Release|Any CPU
{06C9E60E-D449-41A7-9BF0-A829AAF5D214}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{06C9E60E-D449-41A7-9BF0-A829AAF5D214}.Debug|Any CPU.Build.0 = Debug|Any CPU
{06C9E60E-D449-41A7-9BF0-A829AAF5D214}.Release|Any CPU.ActiveCfg = Release|Any CPU
{06C9E60E-D449-41A7-9BF0-A829AAF5D214}.Release|Any CPU.Build.0 = Release|Any CPU
{E5595DE0-B177-4078-AD10-8D3135014838}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E5595DE0-B177-4078-AD10-8D3135014838}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E5595DE0-B177-4078-AD10-8D3135014838}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E5595DE0-B177-4078-AD10-8D3135014838}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0081B29F-FCF8-45FA-A5DF-732CD3ED2E11}
SolutionGuid = {A65DB16F-877D-4586-A9F3-8BBBFBAF5CEB}
EndGlobalSection
EndGlobal

@ -1,133 +0,0 @@
using System;
using System.Collections.Generic;
using ZeroLevel.DocumentObjectModel;
using ZeroLevel.Services.Serialization;
namespace ZeroLevel.Models
{
/// <summary>
/// Binary data represantation
/// </summary>
public class BinaryDocument :
IBinarySerializable,
IEquatable<BinaryDocument>,
ICloneable
{
/// <summary>
/// Id
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// File name
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Content type (pdf, doc, etc.)
/// </summary>
public string ContentType { get; set; }
/// <summary>
/// Content
/// </summary>
public byte[] Document { get; set; }
/// <summary>
/// Creation date
/// </summary>
public DateTime Created { get; set; }
/// <summary>
/// Optional headers
/// </summary>
public List<Header> Headers { get; set; }
/// <summary>
/// Categories
/// </summary>
public List<Category> Categories { get; set; }
#region Ctors
public BinaryDocument()
{
Created = DateTime.Now;
Headers = new List<Header>();
Categories = new List<Category>();
}
public BinaryDocument(BinaryDocument other)
{
var data = MessageSerializer.Serialize(other);
using (var reader = new MemoryStreamReader(data))
{
Deserialize(reader);
}
}
#endregion Ctors
#region IBinarySerializable
public void Serialize(IBinaryWriter writer)
{
writer.WriteGuid(this.Id);
writer.WriteString(this.FileName);
writer.WriteString(this.ContentType);
writer.WriteBytes(this.Document);
writer.WriteDateTime(this.Created);
writer.WriteCollection(this.Headers);
writer.WriteCollection(this.Categories);
}
public void Deserialize(IBinaryReader reader)
{
this.Id = reader.ReadGuid();
this.FileName = reader.ReadString();
this.ContentType = reader.ReadString();
this.Document = reader.ReadBytes();
this.Created = reader.ReadDateTime() ?? DateTime.Now;
this.Headers = reader.ReadCollection<Header>();
this.Categories = reader.ReadCollection<Category>();
}
#endregion IBinarySerializable
#region Equals & Hash
public override bool Equals(object obj)
{
return this.Equals(obj as BinaryDocument);
}
public bool Equals(BinaryDocument other)
{
if (this == null)
throw new NullReferenceException();
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
if (this.GetType() != other.GetType()) return false;
if (this.Id != other.Id) return false;
if (DateTime.Compare(this.Created, other.Created) != 0) return false;
if (ArrayExtensions.UnsafeEquals(this.Document, other.Document) == false) return false;
if (string.Compare(this.ContentType, other.ContentType) != 0) return false;
if (string.Compare(this.FileName, other.FileName) != 0) return false;
if (this.Headers.NoOrderingEquals(other.Headers) == false) return false;
if (this.Categories.NoOrderingEquals(other.Categories) == false) return false;
return true;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
#endregion Equals & Hash
public object Clone()
{
return new BinaryDocument(this);
}
}
}

@ -1,35 +0,0 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ZeroLevel")]
[assembly: AssemblyDescription("Infrastructure layer library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ogoun")]
[assembly: AssemblyProduct("ZeroLevel")]
[assembly: AssemblyCopyright("Copyright © Ogoun 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("658210ea-6b29-4c1b-a13c-3bc7edc2770e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -1,133 +0,0 @@
using System;
using System.ServiceProcess;
using System.Threading;
namespace ZeroLevel.Services.Applications
{
public abstract class BaseWindowsService
: ServiceBase, IZeroService
{
public string Name { get; protected set; }
protected BaseWindowsService()
{
Name = GetType().Name;
}
protected BaseWindowsService(string name)
{
Name = name;
}
public ZeroServiceState State => _state;
private ZeroServiceState _state;
private ManualResetEvent InteraciveModeWorkingFlag = new ManualResetEvent(false);
public void InteractiveStart(string[] args)
{
InteraciveModeWorkingFlag.Reset();
OnStart(args);
try
{
while (false == InteraciveModeWorkingFlag.WaitOne(2000))
{
}
}
catch { }
}
#region IZeroService
public abstract void StartAction();
public abstract void StopAction();
public abstract void PauseAction();
public abstract void ResumeAction();
public abstract void DisposeResources();
#endregion IZeroService
#region Windows service
protected override void OnStart(string[] args)
{
if (_state == ZeroServiceState.Initialized)
{
try
{
StartAction();
_state = ZeroServiceState.Started;
Log.Debug($"[{Name}] Service started");
}
catch (Exception ex)
{
Log.Fatal(ex, $"[{Name}] Failed to start service");
Stop();
}
}
}
protected override void OnPause()
{
if (_state == ZeroServiceState.Started)
{
try
{
PauseAction();
_state = ZeroServiceState.Paused;
Log.Debug($"[{Name}] Service paused");
}
catch (Exception ex)
{
Log.Fatal(ex, $"[{Name}] Failed to pause service");
Stop();
}
}
}
protected override void OnContinue()
{
if (_state == ZeroServiceState.Paused)
{
try
{
ResumeAction();
_state = ZeroServiceState.Started;
Log.Debug($"[{Name}] Service continue work after pause");
}
catch (Exception ex)
{
Log.Fatal(ex, $"[{Name}] Failed to continue work service after pause");
Stop();
}
}
}
protected override void OnStop()
{
if (_state != ZeroServiceState.Stopped)
{
_state = ZeroServiceState.Stopped;
try
{
StopAction();
Log.Debug($"[{Name}] Service stopped");
}
catch (Exception ex)
{
Log.Fatal(ex, $"[{Name}] Failed to stop service");
}
finally
{
InteraciveModeWorkingFlag?.Set();
}
}
}
#endregion Windows service
}
}

@ -1,114 +0,0 @@
using System;
using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;
namespace ZeroLevel.Services.Applications
{
internal static class BasicServiceInstaller
{
private class InstallOptions
{
public string ServiceName;
public string ServiceDisplayName;
public string ServiceDescription;
public ServiceStartMode ServiceStartType = ServiceStartMode.Automatic;
public ServiceAccount ServiceAccountType = ServiceAccount.LocalSystem;
public string ServiceUserName;
public string ServiceUserPassword;
}
private static InstallOptions ReadOptions(IConfiguration configuration)
{
if (configuration == null)
{
configuration = Configuration.Default;
}
var options = new InstallOptions();
if (configuration.Contains("ServiceDescription"))
{
options.ServiceDescription = configuration.First("ServiceDescription");
}
if (configuration.Contains("ServiceName"))
{
options.ServiceName = configuration.First("ServiceName");
}
if (configuration.Contains("ServiceDisplayName"))
{
options.ServiceDisplayName = configuration.First("ServiceDisplayName");
}
else
{
options.ServiceDisplayName = options.ServiceName;
}
if (configuration.Contains("ServiceUserName"))
{
options.ServiceUserName = configuration.First("ServiceUserName");
}
if (configuration.Contains("ServiceUserPassword"))
{
options.ServiceUserPassword = configuration.First("ServiceUserPassword");
}
if (configuration.Contains("ServiceStartType"))
{
var startType = configuration.First("ServiceStartType");
ServiceStartMode mode;
if (Enum.TryParse(startType, out mode))
{
options.ServiceStartType = mode;
}
else
{
options.ServiceStartType = ServiceStartMode.Automatic;
}
}
if (configuration.Contains("ServiceAccountType"))
{
var accountType = configuration.First("ServiceAccountType");
ServiceAccount type;
if (Enum.TryParse(accountType, out type))
{
options.ServiceAccountType = type;
}
else
{
options.ServiceAccountType = ServiceAccount.LocalService;
}
}
return options;
}
public static void Install(IConfiguration configuration)
{
CreateInstaller(ReadOptions(configuration)).Install(new Hashtable());
}
public static void Uninstall(IConfiguration configuration)
{
CreateInstaller(ReadOptions(configuration)).Uninstall(null);
}
private static Installer CreateInstaller(InstallOptions options)
{
var installer = new TransactedInstaller();
installer.Installers.Add(new ServiceInstaller()
{
ServiceName = options.ServiceName,
DisplayName = options.ServiceDisplayName,
StartType = options.ServiceStartType,
Description = options.ServiceDescription
});
installer.Installers.Add(new ServiceProcessInstaller
{
Account = options.ServiceAccountType,
Username = (options.ServiceAccountType == ServiceAccount.User) ? options.ServiceUserName : null,
Password = (options.ServiceAccountType == ServiceAccount.User) ? options.ServiceUserPassword : null
});
var installContext = new InstallContext(options.ServiceName + ".install.log", null);
installContext.Parameters["assemblypath"] = Configuration.AppLocation;
installer.Context = installContext;
return installer;
}
}
}

@ -1,168 +0,0 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using ZeroLevel.Services.Applications;
namespace ZeroLevel
{
public static class Bootstrap
{
static Bootstrap()
{
// Tricks for minimize config changes for dependency resolve
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
try
{
Log.Debug($"[Bootstrap] Resolve assembly '{args.Name}'");
if (args.Name.StartsWith("Newtonsoft.Json", StringComparison.Ordinal))
{
return Assembly.LoadFile(Path.Combine(Configuration.BaseDirectory, "Newtonsoft.Json.dll"));
}
else if (args.Name.Equals("Microsoft.Owin", StringComparison.Ordinal))
{
return Assembly.LoadFile(Path.Combine(Configuration.BaseDirectory, "Microsoft.Owin.dll"));
}
var candidates = Directory.GetFiles(Path.Combine(Configuration.BaseDirectory), args.Name, SearchOption.TopDirectoryOnly);
if (candidates != null && candidates.Any())
{
return Assembly.LoadFile(candidates.First());
}
}
catch (Exception ex)
{
Log.Error(ex, $"[Bootstrap] Fault load assembly '{args.Name}'");
}
return null;
}
/// <summary>
/// Self-install as windows service
/// </summary>
private static void InstallApplication()
{
try
{
Configuration.Save(Configuration.ReadFromApplicationConfig());
Log.AddTextFileLogger("install.log");
BasicServiceInstaller.Install(Configuration.Default);
}
catch (Exception ex)
{
Log.Fatal(ex, "[Bootstrap] Fault service install");
}
}
/// <summary>
/// Uninstall from windows services
/// </summary>
private static void UninstallApplication()
{
try
{
Configuration.Save(Configuration.ReadFromApplicationConfig());
Log.AddTextFileLogger("uninstall.log");
BasicServiceInstaller.Uninstall(Configuration.Default);
}
catch (Exception ex)
{
Log.Fatal(ex, "[Bootstrap] Fault service uninstall");
}
}
public static void Startup<T>(string[] args, Func<bool> preStartConfiguration = null, Func<bool> postStartConfiguration = null)
where T : IZeroService, new()
{
IZeroService service = null;
var cmd = Configuration.ReadFromCommandLine(args);
if (cmd.Contains("install", "setup"))
{
InstallApplication();
}
else if (cmd.Contains("uninstall", "remove"))
{
UninstallApplication();
}
else
{
Configuration.Save(Configuration.ReadFromApplicationConfig());
Log.CreateLoggingFromConfiguration(Configuration.Default);
if (preStartConfiguration != null)
{
try
{
if (preStartConfiguration() == false)
{
Log.SystemInfo("[Bootstrap] Service start canceled, because custom preconfig return false");
return;
}
}
catch (Exception ex)
{
Log.SystemError(ex, "[Bootstrap] Service start canceled, preconfig faulted");
return;
}
}
try
{
service = new T();
}
catch (Exception ex)
{
Log.SystemError(ex, "[Bootstrap] Service start canceled, service constructor call fault");
}
if (postStartConfiguration != null)
{
try
{
if (postStartConfiguration() == false)
{
Log.SystemInfo("[Bootstrap] Service start canceled, because custom postconfig return false");
return;
}
}
catch (Exception ex)
{
Log.SystemError(ex, "[Bootstrap] Service start canceled, postconfig faulted");
return;
}
}
if (Environment.UserInteractive)
{
try
{
Log.Debug("[Bootstrap] The service starting (interactive mode)");
service?.InteractiveStart(args);
Log.Debug("[Bootstrap] The service stopped (interactive mode)");
}
catch (Exception ex)
{
Log.Fatal(ex, "[Bootstrap] The service start in interactive mode was faulted with error");
}
}
else
{
try
{
Log.Debug("[Bootstrap] The service starting (windows service)");
ServiceBase.Run(new ServiceBase[] { service as ServiceBase });
Log.Debug("[Bootstrap] The service stopped (windows service)");
}
catch (Exception ex)
{
Log.Fatal(ex, "[Bootstrap] The service start was faulted with error");
}
}
}
try { Sheduller.Dispose(); } catch (Exception ex) { Log.Error(ex, "[Bootstrap] Dispose default sheduller error"); }
try { Log.Dispose(); } catch (Exception ex) { Log.Error(ex, "[Bootstrap] Dispose log error"); }
try { Injector.Default.Dispose(); Injector.Dispose(); } catch (Exception ex) { Log.Error(ex, "[Bootstrap] Dispose DI containers error"); }
try { service?.DisposeResources(); } catch (Exception ex) { Log.Error(ex, "[Bootstrap] Dispose service error"); }
}
}
}

@ -1,21 +0,0 @@
using System;
namespace ZeroLevel.Services.Applications
{
public interface IZeroService
{
ZeroServiceState State { get; }
void StartAction();
void StopAction();
void PauseAction();
void ResumeAction();
void InteractiveStart(string[] args);
void DisposeResources();
}
}

@ -1,9 +1,10 @@
using ZeroLevel.Network;
using System;
using ZeroLevel.Network;
namespace ZeroLevel.Services.Applications
{
public abstract class BaseWindowsExService
: BaseWindowsService, IExchangeService
public abstract class BaseZeroExchangeService
: BaseZeroService, IExchangeService
{
public string Key { get; private set; }
public string Version { get; private set; }
@ -14,7 +15,7 @@ namespace ZeroLevel.Services.Applications
protected Exchange Exchange { get; }
protected BaseWindowsExService(IConfiguration configuration = null)
protected BaseZeroExchangeService(IConfiguration configuration = null)
: base()
{
_config = configuration ?? Configuration.Default;
@ -100,7 +101,7 @@ namespace ZeroLevel.Services.Applications
public string Endpoint { get; private set; }
public override void DisposeResources()
protected override void StopAction()
{
this.Exchange.Dispose();
}

@ -0,0 +1,69 @@
using System;
using System.Threading;
namespace ZeroLevel.Services.Applications
{
public abstract class BaseZeroService
: IZeroService
{
public string Name { get; protected set; }
public ZeroServiceState State => _state;
private ZeroServiceState _state;
protected BaseZeroService()
{
Name = GetType().Name;
}
protected BaseZeroService(string name)
{
Name = name;
}
private ManualResetEvent InteraciveModeWorkingFlag = new ManualResetEvent(false);
protected abstract void StartAction();
protected abstract void StopAction();
public void Start()
{
InteraciveModeWorkingFlag.Reset();
if (_state == ZeroServiceState.Initialized)
{
try
{
StartAction();
_state = ZeroServiceState.Started;
Log.Debug($"[{Name}] Service started");
}
catch (Exception ex)
{
Log.Fatal(ex, $"[{Name}] Failed to start service");
InteraciveModeWorkingFlag.Set();
}
}
try
{
while (false == InteraciveModeWorkingFlag.WaitOne(2000))
{
}
}
catch { }
_state = ZeroServiceState.Stopped;
try
{
StopAction();
Log.Debug($"[{Name}] Service stopped");
}
catch (Exception ex)
{
Log.Fatal(ex, $"[{Name}] Failed to stop service");
}
}
public void Stop()
{
InteraciveModeWorkingFlag.Set();
}
}
}

@ -0,0 +1,111 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ZeroLevel
{
public static class Bootstrap
{
static Bootstrap()
{
// Tricks for minimize config changes for dependency resolve
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
try
{
Log.Debug($"[Bootstrap] Resolve assembly '{args.Name}'");
if (args.Name.StartsWith("Newtonsoft.Json", StringComparison.Ordinal))
{
return Assembly.LoadFile(Path.Combine(Configuration.BaseDirectory, "Newtonsoft.Json.dll"));
}
else if (args.Name.Equals("Microsoft.Owin", StringComparison.Ordinal))
{
return Assembly.LoadFile(Path.Combine(Configuration.BaseDirectory, "Microsoft.Owin.dll"));
}
var candidates = Directory.GetFiles(Path.Combine(Configuration.BaseDirectory), args.Name, SearchOption.TopDirectoryOnly);
if (candidates != null && candidates.Any())
{
return Assembly.LoadFile(candidates.First());
}
}
catch (Exception ex)
{
Log.Error(ex, $"[Bootstrap] Fault load assembly '{args.Name}'");
}
return null;
}
public static void Startup<T>(string[] args, Func<bool> preStartConfiguration = null, Func<bool> postStartConfiguration = null)
where T : IZeroService, new()
{
var service = Initialize<T>(args, preStartConfiguration, postStartConfiguration);
if (service != null)
{
service.Start();
Shutdown(service);
}
}
private static IZeroService Initialize<T>(string[] args, Func<bool> preStartConfiguration = null, Func<bool> postStartConfiguration = null)
where T : IZeroService, new()
{
IZeroService service = null;
Configuration.Save(Configuration.ReadFromApplicationConfig());
Log.CreateLoggingFromConfiguration(Configuration.Default);
if (preStartConfiguration != null)
{
try
{
if (preStartConfiguration() == false)
{
Log.SystemInfo("[Bootstrap] Service start canceled, because custom preconfig return false");
return null;
}
}
catch (Exception ex)
{
Log.SystemError(ex, "[Bootstrap] Service start canceled, preconfig faulted");
return null;
}
}
try
{
service = new T();
}
catch (Exception ex)
{
Log.SystemError(ex, "[Bootstrap] Service start canceled, service constructor call fault");
}
if (postStartConfiguration != null)
{
try
{
if (postStartConfiguration() == false)
{
Log.SystemInfo("[Bootstrap] Service start canceled, because custom postconfig return false");
return null;
}
}
catch (Exception ex)
{
Log.SystemError(ex, "[Bootstrap] Service start canceled, postconfig faulted");
return null;
}
}
return service;
}
private static void Shutdown(IZeroService service)
{
try { Sheduller.Dispose(); } catch (Exception ex) { Log.Error(ex, "[Bootstrap] Dispose default sheduller error"); }
try { Log.Dispose(); } catch (Exception ex) { Log.Error(ex, "[Bootstrap] Dispose log error"); }
try { Injector.Default.Dispose(); Injector.Dispose(); } catch (Exception ex) { Log.Error(ex, "[Bootstrap] Dispose DI containers error"); }
try { (service as IDisposable)?.Dispose(); } catch (Exception ex) { Log.Error(ex, $"[Bootstrap] Service {service?.Name} dispose error"); }
}
}
}

@ -1,36 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ZeroLevel.Services.Diagnostics
{
/// <summary>
/// Performs read of stack trace
/// </summary>
public static class StackTraceReader
{
/// <summary>
/// Read current stack trace
/// </summary>
/// <returns>Result - enumerable of tuples as 'Type':'MethodName'</returns>
public static Tuple<string, string>[] ReadFrames()
{
var result = new List<Tuple<string, string>>();
var stackTrace = new StackTrace();
foreach (var frame in stackTrace.GetFrames() ?? Enumerable.Empty<StackFrame>())
{
var method = frame.GetMethod();
if (method != null && method.DeclaringType != null)
{
var type = method.DeclaringType.Name;
if (false == type.Equals("StackTraceReader", StringComparison.Ordinal))
{
result.Add(new Tuple<string, string>(type, method.Name));
}
}
}
return result.ToArray();
}
}
}

@ -1,76 +0,0 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace ZeroLevel.Services.Drawing
{
public static class TextPainter
{
#region Drawing text along lines
public static void DrawOnSegment(Graphics gr, Font font,
PointF start_point,
PointF end_point,
string txt,
bool text_above_segment)
{
int start_ch = 0;
// gr.DrawLine(Pens.Green, start_point, end_point);
DrawTextOnSegment(gr, Brushes.Black, font, txt,
ref start_ch, ref start_point, end_point, text_above_segment);
}
// Draw some text along a line segment.
// Leave char_num pointing to the next character to be drawn.
// Leave start_point holding the last point used.
private static void DrawTextOnSegment(Graphics gr, Brush brush, Font font, string txt, ref int first_ch, ref PointF start_point, PointF end_point, bool text_above_segment)
{
float dx = end_point.X - start_point.X;
float dy = end_point.Y - start_point.Y;
float dist = (float)Math.Sqrt(dx * dx + dy * dy);
dx /= dist;
dy /= dist;
// See how many characters will fit.
int last_ch = first_ch;
while (last_ch < txt.Length)
{
string test_string = txt.Substring(first_ch, last_ch - first_ch + 1);
if (gr.MeasureString(test_string, font).Width > dist)
{
// This is one too many characters.
last_ch--;
break;
}
last_ch++;
}
if (last_ch < first_ch) return;
if (last_ch >= txt.Length) last_ch = txt.Length - 1;
string chars_that_fit = txt.Substring(first_ch, last_ch - first_ch + 1);
// Rotate and translate to position the characters.
GraphicsState state = gr.Save();
if (text_above_segment)
{
gr.TranslateTransform(0,
-gr.MeasureString(chars_that_fit, font).Height,
MatrixOrder.Append);
}
float angle = (float)(180 * Math.Atan2(dy, dx) / Math.PI);
if (float.IsNaN(angle)) angle = 0;
gr.RotateTransform(angle, MatrixOrder.Append);
gr.TranslateTransform(start_point.X, start_point.Y, MatrixOrder.Append);
// Draw the characters that fit.
gr.DrawString(chars_that_fit, font, brush, 0, 0);
// Restore the saved state.
gr.Restore(state);
// Update first_ch and start_point.
first_ch = last_ch + 1;
float text_width = gr.MeasureString(chars_that_fit, font).Width;
start_point = new PointF(
start_point.X + dx * text_width,
start_point.Y + dy * text_width);
}
#endregion Drawing text along lines
}
}

@ -41,24 +41,6 @@ namespace ZeroLevel.Services.FileSystem
return folderName;
}
/// <summary>
/// Sets the directory permissions for the account
/// </summary>
/// <param name="folderPath">Directory path</param>
/// <param name="account">Account</param>
/// <param name="right">Access rights</param>
/// <param name="controlType">Access type</param>
public static void SetupFolderPermission(string folderPath, string account,
FileSystemRights right, AccessControlType controlType)
{
DirectoryInfo directory = new DirectoryInfo(folderPath);
DirectorySecurity security = directory.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(account, right,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, controlType));
directory.SetAccessControl(security);
}
#region FileName & Path correction
private static string _invalid_path_characters = new string(Path.GetInvalidPathChars());

@ -335,17 +335,6 @@ namespace ZeroLevel.Services.FileSystem
return archive_file_path;
}
private static void PrepareFolder(string path)
{
if (Directory.Exists(path) == false)
{
Directory.CreateDirectory(path);
FSUtils.SetupFolderPermission(path, $"{Environment.UserDomainName}\\{Environment.UserName}",
FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify,
AccessControlType.Allow);
}
}
private static string PreparePath(string path)
{
if (path.IndexOf(':') == -1)
@ -356,6 +345,13 @@ namespace ZeroLevel.Services.FileSystem
}
#endregion Helpers
private static void PrepareFolder(string path)
{
if (Directory.Exists(path) == false)
{
Directory.CreateDirectory(path);
}
}
public void Dispose()
{
@ -487,10 +483,6 @@ namespace ZeroLevel.Services.FileSystem
if (Directory.Exists(path) == false)
{
Directory.CreateDirectory(path);
FSUtils.SetupFolderPermission(path,
$"{Environment.UserDomainName}\\{Environment.UserName}",
FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify,
AccessControlType.Allow);
}
}

@ -57,8 +57,6 @@ namespace ZeroLevel.Services.FileSystem
{
try
{
FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.AllAccess, file);
perm.Demand();
Log.Debug($"[PeriodicFileSystemWatcher] Find new file {file}");
if (FSUtils.IsFileLocked(new FileInfo(file)))
{

@ -0,0 +1,13 @@
namespace ZeroLevel
{
public interface IZeroService
{
ZeroServiceState State { get; }
string Name { get; }
void Start();
void Stop();
}
}

@ -1,14 +0,0 @@
using System;
namespace ZeroLevel.Services.Impersonation
{
/// <summary>
/// Interface for classes executing code from user or process rights
/// </summary>
public interface IImpersonationExecutor
{
void ExecuteCode<T>(Action<T> action, T arg);
void ExecuteCode(Action action);
}
}

@ -1,149 +0,0 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security.Principal;
namespace ZeroLevel.Services.Impersonation
{
/// <summary>
/// The class implements the translation of the program execution to the rights of the specified user.
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonation : IDisposable
{
private WindowsImpersonationContext impersonationContext;
#region Private methods
/// <summary>
/// Assigning rights to the current process from the specified process, by copying its token
/// </summary>
/// <param name="hProcess">Process pointer</param>
private void ImpersonateByProcess(IntPtr hProcess)
{
MySafeTokenHandle token;
if (!ImpersonationNativeMethods.OpenProcessToken(hProcess, ImpersonationNativeMethods.TokenDesiredAccess.TOKEN_DUPLICATE, out token))
throw new ApplicationException("Failed to get the process token. Win32 error code: " + Marshal.GetLastWin32Error());
ImpersonateToken(token);
}
/// <summary>
/// The method assigns a duplicate token to the current process.
/// </summary>
/// <param name="token">Token</param>
private void ImpersonateToken(MySafeTokenHandle token)
{
MySafeTokenHandle tokenDuplicate;
WindowsIdentity tempWindowsIdentity;
using (token)
{
if (ImpersonationNativeMethods.DuplicateToken(token, (int)ImpersonationNativeMethods.SecurityImpersonationLevel.SecurityImpersonation, out tokenDuplicate) != 0)
{
using (tokenDuplicate)
{
if (!tokenDuplicate.IsInvalid)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate.DangerousGetHandle());
impersonationContext = tempWindowsIdentity.Impersonate();
return;
}
}
}
else
throw new Exception("Failed to create a duplicate of the specified token. Win32 error code: " + Marshal.GetLastWin32Error());
}
}
#endregion Private methods
#region Public methods
/// <summary>
/// Login as a specified user
/// </summary>
/// <param name="userName">User name</param>
/// <param name="domain">User domain</param>
/// <param name="password">User password</param>
/// <returns>false - if failed to log in with the specified data</returns>
public void ImpersonateByUser(String userName, String domain, String password)
{
MySafeTokenHandle token;
if (ImpersonationNativeMethods.LogonUserA(userName, domain, password, (int)ImpersonationNativeMethods.LogonType.LOGON32_LOGON_INTERACTIVE, (int)ImpersonationNativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT, out token) != 0)
{
ImpersonateToken(token);
}
else
{
throw new Exception("LogonUser failed: " + Marshal.GetLastWin32Error().ToString());
}
}
/// <summary>
/// Login on behalf of the specified user with the authorization method
/// </summary>
/// <param name="userName">Login</param>
/// <param name="domain">Domain</param>
/// <param name="password">Password</param>
/// <param name="logonType">Authorization Type</param>
public void ImpersonateByUser(String userName, String domain, String password, ImpersonationNativeMethods.LogonType logonType)
{
MySafeTokenHandle token;
if (ImpersonationNativeMethods.LogonUserA(userName, domain, password, (int)logonType, (int)ImpersonationNativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT, out token) != 0)
{
ImpersonateToken(token);
}
else
{
throw new Exception("LogonUser failed: " + Marshal.GetLastWin32Error().ToString());
}
}
/// <summary>
/// Copying the rights of the specified process
/// </summary>
/// <param name="ProcessName">Process name</param>
public void ImpersonateByProcess(string ProcessName)
{
Process[] myProcesses = Process.GetProcesses();
foreach (Process currentProcess in myProcesses)
{
if (currentProcess.ProcessName.Equals(ProcessName, StringComparison.OrdinalIgnoreCase))
{
ImpersonateByProcess(currentProcess.Handle);
break;
}
}
}
/// <summary>
/// Copying the rights of the specified process
/// </summary>
/// <param name="ProcessID">Process id</param>
public void ImpersonateByProcess(int ProcessID)
{
Process[] myProcesses = Process.GetProcesses();
foreach (Process currentProcess in myProcesses)
{
if (currentProcess.Id == ProcessID)
{
ImpersonateByProcess(currentProcess.Handle);
break;
}
}
}
#endregion Public methods
/// <summary>
/// When releasing resources, we will return the previous user right
/// </summary>
public void Dispose()
{
impersonationContext?.Undo();
impersonationContext?.Dispose();
GC.SuppressFinalize(this);
}
}
}

@ -1,198 +0,0 @@
using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
namespace ZeroLevel.Services.Impersonation
{
[SuppressUnmanagedCodeSecurity()]
public static class ImpersonationNativeMethods
{
#region P/Invoke enums
/// <summary>
/// Authorization provider
/// </summary>
public enum LogonProvider : int
{
/// <summary>
/// Use the standard logon provider for the system.
/// The default security provider is negotiate, unless you pass NULL for the domain name and the user name
/// is not in UPN format. In this case, the default provider is NTLM.
/// NOTE: Windows 2000/NT: The default security provider is NTLM.
/// </summary>
LOGON32_PROVIDER_DEFAULT = 0,
}
/// <summary>
/// Authorization method
/// </summary>
public enum LogonType : int
{
/// <summary>
/// This logon type is intended for users who will be interactively using the computer, such as a user being logged on
/// by a terminal server, remote shell, or similar process.
/// This logon type has the additional expense of caching logon information for disconnected operations;
/// therefore, it is inappropriate for some client/server applications,
/// such as a mail server.
/// </summary>
LOGON32_LOGON_INTERACTIVE = 2,
/// <summary>
/// This logon type is intended for high performance servers to authenticate plaintext passwords.
/// The LogonUser function does not cache credentials for this logon type.
/// </summary>
LOGON32_LOGON_NETWORK = 3,
/// <summary>
/// This logon type is intended for batch servers, where processes may be executing on behalf of a user without
/// their direct intervention. This type is also for higher performance servers that process many plaintext
/// authentication attempts at a time, such as mail or Web servers.
/// The LogonUser function does not cache credentials for this logon type.
/// </summary>
LOGON32_LOGON_BATCH = 4,
/// <summary>
/// Indicates a service-type logon. The account provided must have the service privilege enabled.
/// </summary>
LOGON32_LOGON_SERVICE = 5,
/// <summary>
/// This logon type is for GINA DLLs that log on users who will be interactively using the computer.
/// This logon type can generate a unique audit record that shows when the workstation was unlocked.
/// </summary>
LOGON32_LOGON_UNLOCK = 7,
/// <summary>
/// This logon type preserves the name and password in the authentication package, which allows the server to make
/// connections to other network servers while impersonating the client. A server can accept plaintext credentials
/// from a client, call LogonUser, verify that the user can access the system across the network, and still
/// communicate with other servers.
/// NOTE: Windows NT: This value is not supported.
/// </summary>
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
/// <summary>
/// This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
/// The new logon session has the same local identifier but uses different credentials for other network connections.
/// NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
/// NOTE: Windows NT: This value is not supported.
/// </summary>
LOGON32_LOGON_NEW_CREDENTIALS = 9,
}
/// <summary>
/// Desired access level to token
/// </summary>
public struct TokenDesiredAccess
{
public static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
public static uint STANDARD_RIGHTS_READ = 0x00020000;
public static uint TOKEN_ASSIGN_PRIMARY = 0x0001;
/// <summary>
/// Allows to create a copy
/// </summary>
public static uint TOKEN_DUPLICATE = 0x0002;
public static uint TOKEN_IMPERSONATE = 0x0004;
public static uint TOKEN_QUERY = 0x0008;
public static uint TOKEN_QUERY_SOURCE = 0x0010;
public static uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
public static uint TOKEN_ADJUST_GROUPS = 0x0040;
public static uint TOKEN_ADJUST_DEFAULT = 0x0080;
public static uint TOKEN_ADJUST_SESSIONID = 0x0100;
public static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
public static uint TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID);
}
/// <summary>
/// The security type is used during the token duplication operation (in the current task)
/// </summary>
public enum SecurityImpersonationLevel : int
{
/// <summary>
/// The server process cannot obtain identification information about the client,
/// and it cannot impersonate the client. It is defined with no value given, and thus,
/// by ANSI C rules, defaults to a value of zero.
/// </summary>
SecurityAnonymous = 0,
/// <summary>
/// The server process can obtain information about the client, such as security identifiers and privileges,
/// but it cannot impersonate the client. This is useful for servers that export their own objects,
/// for example, database products that export tables and views.
/// Using the retrieved client-security information, the server can make access-validation decisions without
/// being able to use other services that are using the client's security context.
/// </summary>
SecurityIdentification = 1,
/// <summary>
/// The server process can impersonate the client's security context on its local system.
/// The server cannot impersonate the client on remote systems.
/// </summary>
SecurityImpersonation = 2,
/// <summary>
/// The server process can impersonate the client's security context on remote systems.
/// NOTE: Windows NT: This impersonation level is not supported.
/// </summary>
SecurityDelegation = 3,
}
#endregion P/Invoke enums
#region P/Invoke
/// <summary>
/// Authorization on behalf of the specified user
/// </summary>
/// <param name="lpszUserName">Username</param>
/// <param name="lpszDomain">Domain</param>
/// <param name="lpszPassword">Password</param>
/// <param name="dwLogonType">Authorization Type</param>
/// <param name="dwLogonProvider">Provider (always 0)</param>
/// <param name="phToken">Token - login result</param>
/// <returns></returns>
[DllImport("advapi32.dll")]
internal static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
out MySafeTokenHandle phToken);
/// <summary>
/// Creating a duplicate token
/// </summary>
/// <param name="hToken">Original token</param>
/// <param name="impersonationLevel"></param>
/// <param name="hNewToken"></param>
/// <returns></returns>
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int DuplicateToken(MySafeTokenHandle hToken,
int impersonationLevel,
out MySafeTokenHandle hNewToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern bool CloseHandle(IntPtr handle);
/// <summary>
/// Attempt to get a token running process
/// </summary>
/// <param name="ProcessHandle">Process pointer</param>
/// <param name="DesiredAccess"></param>
/// <param name="TokenHandle">Token - result</param>
/// <returns></returns>
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out MySafeTokenHandle TokenHandle);
#endregion P/Invoke
}
}

@ -1,26 +0,0 @@
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
namespace ZeroLevel.Services.Impersonation
{
/// <summary>
/// Implementing a safe pointer
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class MySafeTokenHandle
: SafeHandleZeroOrMinusOneIsInvalid
{
private MySafeTokenHandle()
: base(true)
{
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
override protected bool ReleaseHandle()
{
return ImpersonationNativeMethods.CloseHandle(handle);
}
}
}

@ -1,70 +0,0 @@
using System;
namespace ZeroLevel.Services.Impersonation
{
/// <summary>
/// Implements the execution of an code from the rights of the specified process
/// </summary>
public class ProcessImpersonationExecutor
: IImpersonationExecutor
{
private string _processName = string.Empty;
private int _pid = -1;
public ProcessImpersonationExecutor(string processName)
{
_processName = processName;
}
public ProcessImpersonationExecutor(int pid)
{
_pid = pid;
}
/// <summary>
/// Code execution
/// </summary>
public void ExecuteCode<T>(Action<T> action, T arg)
{
using (Impersonation imp = new Impersonation())
{
if (!String.IsNullOrWhiteSpace(_processName))
{
imp.ImpersonateByProcess(_processName);
}
else if (_pid > -1)
{
imp.ImpersonateByProcess(_pid);
}
else
{
throw new Exception("No data to identify the process. To copy the rights of a process, you must specify its name or identifier");
}
action(arg);
}
}
/// <summary>
/// Code execution
/// </summary>
public void ExecuteCode(Action action)
{
using (Impersonation imp = new Impersonation())
{
if (!String.IsNullOrWhiteSpace(_processName))
{
imp.ImpersonateByProcess(_processName);
}
else if (_pid > -1)
{
imp.ImpersonateByProcess(_pid);
}
else
{
throw new Exception("No data to identify the process. To copy the rights of a process, you must specify its name or identifier");
}
action();
}
}
}
}

@ -1,48 +0,0 @@
using System;
namespace ZeroLevel.Services.Impersonation
{
/// <summary>
/// Class executing code with the rights of the specified user
/// </summary>
public class UserImpersonationExecutor
: IImpersonationExecutor
{
private string USR { get; set; }
private string DOMAIN { get; set; }
private string PWD { get; set; }
private ImpersonationNativeMethods.LogonType logonType = ImpersonationNativeMethods.LogonType.LOGON32_LOGON_INTERACTIVE;
public UserImpersonationExecutor(string userName, string domainName, string password)
{
USR = userName;
DOMAIN = domainName;
PWD = password;
}
/// <summary>
/// Code execution
/// </summary>
public void ExecuteCode<T>(Action<T> action, T arg)
{
using (Impersonation imp = new Impersonation())
{
imp.ImpersonateByUser(USR, DOMAIN, PWD, logonType);
action(arg);
}
}
/// <summary>
/// Code execution
/// </summary>
public void ExecuteCode(Action action)
{
using (Impersonation imp = new Impersonation())
{
imp.ImpersonateByUser(USR, DOMAIN, PWD, logonType);
action();
}
}
}
}

@ -405,10 +405,6 @@ namespace ZeroLevel.Services.Logging.Implementation
if (Directory.Exists(path) == false)
{
Directory.CreateDirectory(path);
FSUtils.SetupFolderPermission(path,
$"{Environment.UserDomainName}\\{Environment.UserName}",
FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify,
AccessControlType.Allow);
}
}

@ -1,151 +0,0 @@
using System;
using System.ComponentModel;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
using System.Threading;
namespace ZeroLevel.Services.Reflection
{
/// <summary>
/// Конструктор простейших типов, без методов
/// </summary>
public sealed class DTOTypeBuilder
{
#region Fields
private readonly TypeBuilder _typeBuilder;
#endregion
/// <summary>
/// Конструктор
/// </summary>
/// <param name="typeName">Название создаваемого типа</param>
public DTOTypeBuilder(string typeName)
{
var newAssemblyName = new AssemblyName(Guid.NewGuid().ToString());
var assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(newAssemblyName, AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(newAssemblyName.Name);
_typeBuilder = moduleBuilder.DefineType(typeName,
TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit | TypeAttributes.Serializable |
TypeAttributes.AutoLayout, typeof(object));
var a_ctor = typeof(DataContractAttribute).GetConstructor(new Type[] { });
var a_builder = new CustomAttributeBuilder(a_ctor, new object[] { });
_typeBuilder.SetCustomAttribute(a_builder);
}
public void AppendField<T>(string name)
{
_typeBuilder.DefineField(name, typeof(T), FieldAttributes.Public);
}
public void AppendField<T>(string name, T defaultValue)
{
var builder = _typeBuilder.DefineField(name, typeof(T), FieldAttributes.Public | FieldAttributes.HasDefault);
builder.SetConstant(defaultValue);
}
public void AppendProperty<T>(string name)
{
CreateProperty<T>(name, _typeBuilder, null);
}
public void AppendProperty<T>(string name, T defaultValue)
{
CreateProperty<T>(name, _typeBuilder, null).SetConstant(defaultValue);
}
public void AppendProperty<T>(string name, string description)
{
CreateProperty<T>(name, _typeBuilder, description);
}
public void AppendProperty<T>(string name, string description, T defaultValue)
{
CreateProperty<T>(name, _typeBuilder, description).SetConstant(defaultValue);
}
public void AppendProperty(Type propertyType, string name)
{
CreateProperty(propertyType, name, _typeBuilder, null);
}
public void AppendProperty(Type propertyType, string name, object defaultValue)
{
CreateProperty(propertyType, name, _typeBuilder, null).SetConstant(defaultValue);
}
public void AppendProperty(Type propertyType, string name, string description)
{
CreateProperty(propertyType, name, _typeBuilder, description);
}
public void AppendProperty(Type propertyType, string name, string description, object defaultValue)
{
CreateProperty(propertyType, name, _typeBuilder, description).SetConstant(defaultValue);
}
private static FieldBuilder CreateProperty<T>(string name,
TypeBuilder typeBuilder,
string description)
{
return CreateProperty(typeof(T), name, typeBuilder, description);
}
private static FieldBuilder CreateProperty(Type propertyType, string name,
TypeBuilder typeBuilder,
string description)
{
var backingFieldBuilder = typeBuilder.DefineField("f__" + name.ToLowerInvariant(), propertyType, FieldAttributes.Private);
var propertyBuilder = typeBuilder.DefineProperty(name, PropertyAttributes.HasDefault,
propertyType, new Type[] { propertyType });
// Build setter
var getterMethodBuilder = typeBuilder.DefineMethod("get_" + name,
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
propertyType, Type.EmptyTypes);
var getterIl = getterMethodBuilder.GetILGenerator();
getterIl.Emit(OpCodes.Ldarg_0);
getterIl.Emit(OpCodes.Ldfld, backingFieldBuilder);
getterIl.Emit(OpCodes.Ret);
// Build setter
var setterMethodBuilder = typeBuilder.DefineMethod("set_" + name,
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
null, new[] { propertyType });
var setterIl = setterMethodBuilder.GetILGenerator();
setterIl.Emit(OpCodes.Ldarg_0);
setterIl.Emit(OpCodes.Ldarg_1);
setterIl.Emit(OpCodes.Stfld, backingFieldBuilder);
setterIl.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getterMethodBuilder);
propertyBuilder.SetSetMethod(setterMethodBuilder);
// Set description attribute
if (false == string.IsNullOrWhiteSpace(description))
{
var ctorParams = new[] { typeof(string) };
var classCtorInfo = typeof(DescriptionAttribute).GetConstructor(ctorParams);
var myCABuilder = new CustomAttributeBuilder(classCtorInfo, new object[] { description });
propertyBuilder.SetCustomAttribute(myCABuilder);
}
var a_ctor = typeof(DataMemberAttribute).GetConstructor(new Type[] { });
var a_builder = new CustomAttributeBuilder(a_ctor, new object[] { });
propertyBuilder.SetCustomAttribute(a_builder);
return backingFieldBuilder;
}
/// <summary>
/// Собирает конечный тип
/// </summary>
/// <returns>Готовый тип</returns>
public Type Complete()
{
// Сборка типа
var type = _typeBuilder.CreateType();
// Результат
return type;
}
}
}

@ -1,25 +0,0 @@
using System;
using System.Reflection.Emit;
namespace ZeroLevel.Services.Reflection
{
public static class ReferenceHelpers
{
public static readonly Action<object, Action<IntPtr>> GetPinnedPtr;
static ReferenceHelpers()
{
var dyn = new DynamicMethod("GetPinnedPtr", typeof(void), new[] { typeof(object), typeof(Action<IntPtr>) }, typeof(ReferenceHelpers).Module);
var il = dyn.GetILGenerator();
il.DeclareLocal(typeof(object), true);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Call, typeof(Action<IntPtr>).GetMethod("Invoke"));
il.Emit(OpCodes.Ret);
GetPinnedPtr = (Action<object, Action<IntPtr>>)dyn.CreateDelegate(typeof(Action<object, Action<IntPtr>>));
}
}
}

@ -1,125 +0,0 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using ZeroLevel.Services.Collections;
namespace ZeroLevel.Services.Reflection
{
public static class TypeActivator
{
private static readonly ConcurrentDictionary<Type, Dictionary<string, Delegate>> _withArgumentsConstructorFactories =
new ConcurrentDictionary<Type, Dictionary<string, Delegate>>();
private static readonly IEverythingStorage _withoutArgumentsConstructorFactories = EverythingStorage.Create();
internal static string CreateMethodIdentity(string name, params Type[] argsTypes)
{
var identity = new StringBuilder(name);
identity.Append("(");
if (null != argsTypes)
{
for (var i = 0; i < argsTypes.Length; i++)
{
identity.Append(argsTypes[i].Name);
if ((i + 1) < argsTypes.Length)
identity.Append(".");
}
}
identity.Append(")");
return identity.ToString();
}
public static T Create<T>(params object[] args)
{
var type = typeof(T);
if (false == _withArgumentsConstructorFactories.ContainsKey(type))
{
var d = new Dictionary<string, Delegate>();
foreach (var ctor in type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public))
{
var invoker = MakeFactory(ctor);
if (invoker != null)
d.Add(invoker.Item1, invoker.Item2);
}
_withArgumentsConstructorFactories.AddOrUpdate(type, d, (k, v) => v);
}
var id = CreateMethodIdentity(".ctor",
args == null ? null : args.Select(a => a.GetType()).ToArray());
if (_withArgumentsConstructorFactories[type].ContainsKey(id))
return (T)_withArgumentsConstructorFactories[type][id].DynamicInvoke(args);
return default(T);
}
public static T Create<T>()
where T : new()
{
var type = typeof(T);
if (false == _withoutArgumentsConstructorFactories.ContainsKey<Func<T>>(type.FullName))
{
_withoutArgumentsConstructorFactories.Add<Func<T>>(type.FullName, MakeFactory<T>());
}
return _withoutArgumentsConstructorFactories.
Get<Func<T>>(type.FullName).
Invoke();
}
private static Func<T> MakeFactory<T>()
where T : new()
{
Expression<Func<T>> expr = () => new T();
NewExpression newExpr = (NewExpression)expr.Body;
var method = new DynamicMethod(
name: "lambda",
returnType: newExpr.Type,
parameterTypes: new Type[0],
m: typeof(T).Module,
skipVisibility: true);
ILGenerator ilGen = method.GetILGenerator();
// Constructor for value types could be null
if (newExpr.Constructor != null)
{
ilGen.Emit(OpCodes.Newobj, newExpr.Constructor);
}
else
{
LocalBuilder temp = ilGen.DeclareLocal(newExpr.Type);
ilGen.Emit(OpCodes.Ldloca, temp);
ilGen.Emit(OpCodes.Initobj, newExpr.Type);
ilGen.Emit(OpCodes.Ldloc, temp);
}
ilGen.Emit(OpCodes.Ret);
return (Func<T>)method.CreateDelegate(typeof(Func<T>));
}
private static Tuple<string, Delegate> MakeFactory(ConstructorInfo ctor)
{
var arguments = ctor.GetParameters();
var constructorArgumentTypes = arguments.
Select(a => a.ParameterType).
ToArray();
if (constructorArgumentTypes.Any(t => t.IsPointer)) return null;
var lamdaParameterExpressions = constructorArgumentTypes.
Select(Expression.Parameter).
ToArray();
var constructorParameterExpressions = lamdaParameterExpressions
.Take(constructorArgumentTypes.Length)
.ToArray();
var constructorCallExpression = Expression.New(ctor,
constructorParameterExpressions);
var lambda = Expression.Lambda(constructorCallExpression,
lamdaParameterExpressions);
var identity = CreateMethodIdentity(ctor.Name,
arguments.Select(p => p.ParameterType).ToArray());
return new Tuple<string, Delegate>(identity.ToString(), lambda.Compile());
}
}
}

@ -1,13 +1,12 @@
using System;
namespace ZeroLevel.Services.Applications
namespace ZeroLevel
{
[Flags]
public enum ZeroServiceState : int
{
Initialized = 0,
Started = 1,
Paused = 2,
Stopped = 3
Stopped = 2
}
}

@ -1,56 +0,0 @@
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using Owin;
using OwinTest.Middleware;
using System;
using System.Web.Http;
using ZeroLevel;
namespace OwinTest
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes(new EnableInheritRoutingDirectRouteProvider());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MessageHandlers.Add(new LogRequestAndResponseHandler());
// Require HTTPS
// config.MessageHandlers.Add(new RequireHttpsMessageHandler());
config.EnsureInitialized();
app.UseWebApi(config);
var contentFileServer = new FileServerOptions()
{
EnableDirectoryBrowsing = false,
EnableDefaultFiles = true,
DefaultFilesOptions = { DefaultFileNames = { "index.html" } },
RequestPath = new PathString("/Content"),
FileSystem = new PhysicalFileSystem(@"./Content"),
StaticFileOptions = { ContentTypeProvider = new CustomTypeProvider() }
};
contentFileServer.StaticFileOptions.OnPrepareResponse = (context) =>
{
if (context.OwinContext.Authentication.User == null)
{
context.OwinContext.Response.Redirect("/login");
}
};
app.UseFileServer(contentFileServer);
app.UseErrorPage();
Log.Info("Server started");
}
}
}

@ -1,383 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{37020D8D-34E8-4EC3-A447-8396D5080457}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ZeroLevel</RootNamespace>
<AssemblyName>ZeroLevel</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<LangVersion>7.1</LangVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>none</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<LangVersion>7.1</LangVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.IO.Compression.FileSystem" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Models\BaseModel.cs" />
<Compile Include="Models\BinaryDocument.cs" />
<Compile Include="Models\IEntity.cs" />
<Compile Include="Models\InvokeResult.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\Application\BaseWindowsExService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Services\Application\BaseWindowsService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Services\Application\BasicServiceInstaller.cs" />
<Compile Include="Services\Application\Bootstrap.cs" />
<Compile Include="Services\Application\IZeroService.cs" />
<Compile Include="Services\Application\ZeroServiceState.cs" />
<Compile Include="Services\Async\AsyncConditionVariable.cs" />
<Compile Include="Services\Async\AsyncHelper.cs" />
<Compile Include="Services\Async\AsyncLock.cs" />
<Compile Include="Services\Async\AsyncManualResetEvent.cs" />
<Compile Include="Services\Async\AsyncMonitor.cs" />
<Compile Include="Services\Async\AsyncProducerConsumerQueue.cs" />
<Compile Include="Services\Async\AsyncReaderWriterLock.cs" />
<Compile Include="Services\Async\AsyncSemaphore.cs" />
<Compile Include="Services\Async\AsyncWaitQueue.cs" />
<Compile Include="Services\Async\CancellationTokenHelpers.cs" />
<Compile Include="Services\Async\CancellationTokenTaskSource.cs" />
<Compile Include="Services\Async\Deque.cs" />
<Compile Include="Services\Async\ExceptionHelpers.cs" />
<Compile Include="Services\Async\IdManager.cs" />
<Compile Include="Services\Async\NormalizedCancellationToken.cs" />
<Compile Include="Services\Async\TaskCompletionSource.cs" />
<Compile Include="Services\Async\TaskCompletionSourceExtensions.cs" />
<Compile Include="Services\Async\TaskConstants.cs" />
<Compile Include="Services\Async\TaskExtensions.cs" />
<Compile Include="Services\Async\TaskShim.cs" />
<Compile Include="Services\Collections\EverythingStorage.cs" />
<Compile Include="Services\Collections\IEverythingStorage.cs" />
<Compile Include="Services\Collections\RoundRobinCollection.cs" />
<Compile Include="Services\Collections\RoundRobinOverCollection.cs" />
<Compile Include="Services\DependencyInjection\Container.cs" />
<Compile Include="Services\DependencyInjection\ContainerFactory.cs" />
<Compile Include="Services\DependencyInjection\Contracts\ICompositionProvider.cs" />
<Compile Include="Services\DependencyInjection\Contracts\IContainer.cs" />
<Compile Include="Services\DependencyInjection\Contracts\IContainerFactory.cs" />
<Compile Include="Services\DependencyInjection\Contracts\IContainerInstanceRegister.cs" />
<Compile Include="Services\DependencyInjection\Contracts\IContainerRegister.cs" />
<Compile Include="Services\DependencyInjection\Contracts\IParameterStorage.cs" />
<Compile Include="Services\DependencyInjection\Contracts\IResolver.cs" />
<Compile Include="Services\DependencyInjection\Injector.cs" />
<Compile Include="Services\DependencyInjection\Internal\ConstructorMetadata.cs" />
<Compile Include="Services\DependencyInjection\Internal\ConstructorParameter.cs" />
<Compile Include="Services\DependencyInjection\Internal\ResolveTypeInfo.cs" />
<Compile Include="Services\DependencyInjection\ParameterAttribute.cs" />
<Compile Include="Services\DependencyInjection\ResolveAttribute.cs" />
<Compile Include="Services\Diagnostics\StackTraceReader.cs" />
<Compile Include="Services\DOM\Contracts\IContentReader.cs" />
<Compile Include="Services\DOM\Contracts\IMetadataReader.cs" />
<Compile Include="Services\DOM\DSL\Contexts\TBlockContext.cs" />
<Compile Include="Services\DOM\DSL\Contexts\TContext.cs" />
<Compile Include="Services\DOM\DSL\Contexts\TElementContext.cs" />
<Compile Include="Services\DOM\DSL\Contexts\TFunctionContext.cs" />
<Compile Include="Services\DOM\DSL\Contexts\TPropertyContext.cs" />
<Compile Include="Services\DOM\DSL\Contexts\TRootContext.cs" />
<Compile Include="Services\DOM\DSL\Contracts\ISpecialTableBuilder.cs" />
<Compile Include="Services\DOM\DSL\Contracts\TCloneable.cs" />
<Compile Include="Services\DOM\DSL\Model\DOMRenderElementCounter.cs" />
<Compile Include="Services\DOM\DSL\Model\TChar.cs" />
<Compile Include="Services\DOM\DSL\Model\TContentElement.cs" />
<Compile Include="Services\DOM\DSL\Model\TEnvironment.cs" />
<Compile Include="Services\DOM\DSL\Model\TFlowRules.cs" />
<Compile Include="Services\DOM\DSL\Model\TRenderOptions.cs" />
<Compile Include="Services\DOM\DSL\Services\PlainTextTableBuilder.cs" />
<Compile Include="Services\DOM\DSL\Services\SpecialTableBuilderFactory.cs" />
<Compile Include="Services\DOM\DSL\Services\TContainer.cs" />
<Compile Include="Services\DOM\DSL\Services\TContainerFactory.cs" />
<Compile Include="Services\DOM\DSL\Services\TContentToStringConverter.cs" />
<Compile Include="Services\DOM\DSL\Services\TRender.cs" />
<Compile Include="Services\DOM\DSL\Services\TStringReader.cs" />
<Compile Include="Services\DOM\DSL\TEngine.cs" />
<Compile Include="Services\DOM\DSL\Tokens\TBlockToken.cs" />
<Compile Include="Services\DOM\DSL\Tokens\TElementToken.cs" />
<Compile Include="Services\DOM\DSL\Tokens\TFunctionToken.cs" />
<Compile Include="Services\DOM\DSL\Tokens\TPropertyToken.cs" />
<Compile Include="Services\DOM\DSL\Tokens\TSystemToken.cs" />
<Compile Include="Services\DOM\DSL\Tokens\TTextToken.cs" />
<Compile Include="Services\DOM\DSL\Tokens\TToken.cs" />
<Compile Include="Services\DOM\Model\Agency.cs" />
<Compile Include="Services\DOM\Model\AttachContent.cs" />
<Compile Include="Services\DOM\Model\Assotiation.cs" />
<Compile Include="Services\DOM\Model\AssotiationRelation.cs" />
<Compile Include="Services\DOM\Model\Category.cs" />
<Compile Include="Services\DOM\Model\ContentType.cs" />
<Compile Include="Services\DOM\Model\DescriptiveMetadata.cs" />
<Compile Include="Services\DOM\Model\Document.cs" />
<Compile Include="Services\DOM\Model\FlowContent.cs" />
<Compile Include="Services\DOM\Model\Flow\Audio.cs" />
<Compile Include="Services\DOM\Model\Flow\Audioplayer.cs" />
<Compile Include="Services\DOM\Model\Flow\Column.cs" />
<Compile Include="Services\DOM\Model\Flow\ContentElement.cs" />
<Compile Include="Services\DOM\Model\Flow\ContentElementType.cs" />
<Compile Include="Services\DOM\Model\Flow\FlowAlign.cs" />
<Compile Include="Services\DOM\Model\Flow\FormContent.cs" />
<Compile Include="Services\DOM\Model\Flow\Gallery.cs" />
<Compile Include="Services\DOM\Model\Flow\IContentElement.cs" />
<Compile Include="Services\DOM\Model\Flow\Image.cs" />
<Compile Include="Services\DOM\Model\Flow\Link.cs" />
<Compile Include="Services\DOM\Model\Flow\List.cs" />
<Compile Include="Services\DOM\Model\Flow\Paragraph.cs" />
<Compile Include="Services\DOM\Model\Flow\Quote.cs" />
<Compile Include="Services\DOM\Model\Flow\Row.cs" />
<Compile Include="Services\DOM\Model\Flow\Section.cs" />
<Compile Include="Services\DOM\Model\Flow\SourceType.cs" />
<Compile Include="Services\DOM\Model\Flow\Table.cs" />
<Compile Include="Services\DOM\Model\Flow\Text.cs" />
<Compile Include="Services\DOM\Model\Flow\TextFormatting.cs" />
<Compile Include="Services\DOM\Model\Flow\TextSize.cs" />
<Compile Include="Services\DOM\Model\Flow\TextStyle.cs" />
<Compile Include="Services\DOM\Model\Flow\Video.cs" />
<Compile Include="Services\DOM\Model\Flow\Videoplayer.cs" />
<Compile Include="Services\DOM\Model\Header.cs" />
<Compile Include="Services\DOM\Model\Identifier.cs" />
<Compile Include="Services\DOM\Model\Priority.cs" />
<Compile Include="Services\DOM\Model\Tag.cs" />
<Compile Include="Services\DOM\Model\TagMetadata.cs" />
<Compile Include="Services\DOM\Services\ContentBuilder.cs" />
<Compile Include="Services\DOM\Services\ContentElementSerializer.cs" />
<Compile Include="Services\DOM\Services\DocumentContentReader.cs" />
<Compile Include="Services\DOM\Services\LanguageParser.cs" />
<Compile Include="Services\Drawing\TextPainter.cs" />
<Compile Include="Services\Encryption\FastObfuscator.cs" />
<Compile Include="Services\Extensions\ArrayExtensions.cs" />
<Compile Include="Services\Extensions\BitConverterExtensions.cs" />
<Compile Include="Services\Extensions\CollectionComparsionExtensions.cs" />
<Compile Include="Services\Collections\FixSizeQueue.cs" />
<Compile Include="Services\Collections\IFixSizeQueue.cs" />
<Compile Include="Services\Config\BaseConfiguration.cs" />
<Compile Include="Services\Config\BaseConfigurationSet.cs" />
<Compile Include="Services\Config\Configuration.cs" />
<Compile Include="Services\Config\IConfiguration.cs" />
<Compile Include="Services\Config\IConfigurationReader.cs" />
<Compile Include="Services\Config\IConfigurationSet.cs" />
<Compile Include="Services\Config\IConfigurationWriter.cs" />
<Compile Include="Services\Config\Implementation\ApplicationConfigReader.cs" />
<Compile Include="Services\Config\Implementation\AppWebConfigReader.cs" />
<Compile Include="Services\Config\Implementation\CommandLineReader.cs" />
<Compile Include="Services\Config\Implementation\IniFileReader.cs" />
<Compile Include="Services\Config\Implementation\IniFileWriter.cs" />
<Compile Include="Services\Encryption\RijndaelEncryptor.cs" />
<Compile Include="Services\Extensions\DateTimeExtensions.cs" />
<Compile Include="Services\Extensions\EndpointExtensions.cs" />
<Compile Include="Services\Extensions\EnumerableExtensions.cs" />
<Compile Include="Services\Extensions\EnumExtensions.cs" />
<Compile Include="Services\Extensions\FPCommon.cs" />
<Compile Include="Services\Extensions\LinqExtension.cs" />
<Compile Include="Services\Extensions\Monades.cs" />
<Compile Include="Services\Extensions\StringExtensions.cs" />
<Compile Include="Services\Extensions\TypeExtensions.cs" />
<Compile Include="Services\FileSystem\FileArchive.cs" />
<Compile Include="Services\FileSystem\FileMeta.cs" />
<Compile Include="Services\FileSystem\FSUtils.cs" />
<Compile Include="Services\FileSystem\PeriodicFileSystemWatcher.cs" />
<Compile Include="Services\IdGenerator.cs" />
<Compile Include="Services\Impersonation\IImpersonationExecutor.cs" />
<Compile Include="Services\Impersonation\Impersonation.cs" />
<Compile Include="Services\Impersonation\ImpersonationNativeMethods.cs" />
<Compile Include="Services\Impersonation\MySafeTokenHandle.cs" />
<Compile Include="Services\Impersonation\ProcessImpersonationExecutor.cs" />
<Compile Include="Services\Impersonation\UserImpersonationExecutor.cs" />
<Compile Include="Services\Invokation\IInvokeWrapper.cs" />
<Compile Include="Services\Invokation\Invoker.cs" />
<Compile Include="Services\Invokation\InvokeWrapper.cs" />
<Compile Include="Services\Logging\FixSizeLogMessageBuffer.cs" />
<Compile Include="Services\Logging\ILog.cs" />
<Compile Include="Services\Logging\ILogComposer.cs" />
<Compile Include="Services\Logging\ILogger.cs" />
<Compile Include="Services\Logging\ILogMessageBuffer.cs" />
<Compile Include="Services\Logging\Implementation\ConsoleLogger.cs" />
<Compile Include="Services\Logging\Implementation\DelegateLogger.cs" />
<Compile Include="Services\Logging\Implementation\EncryptedFileLog.cs" />
<Compile Include="Services\Logging\Implementation\TextFileLogger.cs" />
<Compile Include="Services\Logging\Log.cs" />
<Compile Include="Services\Logging\LogLevel.cs" />
<Compile Include="Services\Logging\LogLevelNameMapping.cs" />
<Compile Include="Services\Logging\LogRouterr.cs" />
<Compile Include="Services\Logging\NoLimitedLogMessageBuffer.cs" />
<Compile Include="Services\Network\Contract\IExClient.cs" />
<Compile Include="Services\Network\Contract\IExService.cs" />
<Compile Include="Services\Network\Contract\IZBackward.cs" />
<Compile Include="Services\Network\Contract\IZObservableServer.cs" />
<Compile Include="Services\Network\Contract\IZTransport.cs" />
<Compile Include="Services\Network\ExchangeTransportFactory.cs" />
<Compile Include="Services\Network\Services\DiscoveryClient.cs" />
<Compile Include="Services\Network\Services\Exchange.cs" />
<Compile Include="Services\Network\Services\ExServiceHost.cs" />
<Compile Include="Services\Network\Contract\IDiscoveryClient.cs" />
<Compile Include="Services\Network\Contract\IExchangeService.cs" />
<Compile Include="Services\Network\Models\ExchangeAttributes.cs" />
<Compile Include="Services\Network\Models\ExServiceInfo.cs" />
<Compile Include="Services\Network\Models\RequestInfo.cs" />
<Compile Include="Services\Network\Models\ServiceEndpointInfo.cs" />
<Compile Include="Services\Network\Models\ServiceEndpointsInfo.cs" />
<Compile Include="Services\Network\Models\ZTransportStatus.cs" />
<Compile Include="Services\Network\NetworkStats.cs" />
<Compile Include="Services\Network\Services\ExClient.cs" />
<Compile Include="Services\Network\Services\ExRouter.cs" />
<Compile Include="Services\Network\Services\ExService.cs" />
<Compile Include="Services\Network\Services\FrameBuilder.cs" />
<Compile Include="Services\Network\Services\FrameExchange.cs" />
<Compile Include="Services\Network\Services\ZExSocketObservableServer.cs" />
<Compile Include="Services\Network\NetUtils.cs" />
<Compile Include="Services\Network\Models\Frame.cs" />
<Compile Include="Services\Network\Services\FrameParser.cs" />
<Compile Include="Services\Network\NetworkStreamDataObfuscator.cs" />
<Compile Include="Services\Network\ZBaseNetwork.cs" />
<Compile Include="Services\Network\ZSocketClient.cs" />
<Compile Include="Services\Network\ZSocketServer.cs" />
<Compile Include="Services\Network\ZSocketServerClient.cs" />
<Compile Include="Services\ObjectMapping\IMapper.cs" />
<Compile Include="Services\ObjectMapping\IMemberInfo.cs" />
<Compile Include="Services\ObjectMapping\MapFieldInfo.cs" />
<Compile Include="Services\ObjectMapping\TypeMapper.cs" />
<Compile Include="Services\Pools\ObjectPool.cs" />
<Compile Include="Services\Queries\AndQuery.cs" />
<Compile Include="Services\Queries\BaseQuery.cs" />
<Compile Include="Services\Queries\Builder\IQueryBuilder.cs" />
<Compile Include="Services\Queries\Builder\MemoryStorageQueryBuilder.cs" />
<Compile Include="Services\Queries\IQuery.cs" />
<Compile Include="Services\Queries\NotQuery.cs" />
<Compile Include="Services\Queries\OrQuery.cs" />
<Compile Include="Services\Queries\Query.cs" />
<Compile Include="Services\Queries\QueryOp.cs" />
<Compile Include="Services\Queries\QueryOperation.cs" />
<Compile Include="Services\Queries\Storage\IRealQuery.cs" />
<Compile Include="Services\Queries\Storage\IStorage.cs" />
<Compile Include="Services\Queries\Storage\MemoryStorage.cs" />
<Compile Include="Services\Queries\Storage\QueryResult.cs" />
<Compile Include="Services\Reflection\DTOTypeBuilder.cs" />
<Compile Include="Services\Reflection\ReferenceHelper.cs" />
<Compile Include="Services\Reflection\StringToTypeConverter.cs" />
<Compile Include="Services\Reflection\TypeActivator.cs" />
<Compile Include="Services\Reflection\TypeGetterSetterBuilder.cs" />
<Compile Include="Services\Reflection\TypeHelpers.cs" />
<Compile Include="Services\Semantic\Contracts\ILexer.cs" />
<Compile Include="Services\Semantic\Contracts\ILexProvider.cs" />
<Compile Include="Services\Semantic\Contracts\Languages.cs" />
<Compile Include="Services\Semantic\Contracts\LexToken.cs" />
<Compile Include="Services\Semantic\Contracts\WordToken.cs" />
<Compile Include="Services\Semantic\Helpers\NGramms.cs" />
<Compile Include="Services\Semantic\Helpers\StopWords.cs" />
<Compile Include="Services\Semantic\Helpers\TextAnalizer.cs" />
<Compile Include="Services\Semantic\LexProvider.cs" />
<Compile Include="Services\Semantic\LexProviderFactory.cs" />
<Compile Include="Services\Semantic\Snowball\Among.cs" />
<Compile Include="Services\Semantic\Snowball\CzechStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\DanishStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\DutchStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\EnglishStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\FinnishStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\FrenchStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\GermanStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\HungarianStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\ItalianStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\NorwegianStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\PortugalStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\RomanianStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\RussianStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\SpanishStemmer.cs" />
<Compile Include="Services\Semantic\Snowball\StemmerOperations.cs" />
<Compile Include="Services\Semantic\WordLexer.cs" />
<Compile Include="Services\Serialization\IBinaryReader.cs" />
<Compile Include="Services\Serialization\IBinarySerializable.cs" />
<Compile Include="Services\Serialization\IBinaryWriter.cs" />
<Compile Include="Services\Serialization\JsonEscaper.cs" />
<Compile Include="Services\Serialization\MemoryStreamReader.cs" />
<Compile Include="Services\Serialization\MemoryStreamWriter.cs" />
<Compile Include="Services\Serialization\MessageSerializer.cs" />
<Compile Include="Services\Serialization\PrimitiveTypeSerializer.cs" />
<Compile Include="Services\Shedulling\AsyncShedullerImpl.cs" />
<Compile Include="Services\Shedulling\DateTimeAsyncSheduller.cs" />
<Compile Include="Services\Shedulling\DateTimeSheduller.cs" />
<Compile Include="Services\Shedulling\ExpiredAsyncObject.cs" />
<Compile Include="Services\Shedulling\ExpiredObject.cs" />
<Compile Include="Services\Shedulling\IAsyncSheduller.cs" />
<Compile Include="Services\Shedulling\IExpirationAsyncSheduller.cs" />
<Compile Include="Services\Shedulling\IExpirationSheduller.cs" />
<Compile Include="Services\Shedulling\ISheduller.cs" />
<Compile Include="Services\Shedulling\Sheduller.cs" />
<Compile Include="Services\Shedulling\ShedullerImpl.cs" />
<Compile Include="Services\Specification\AndSpecification.cs" />
<Compile Include="Services\Specification\BaseNamedSpecification.cs" />
<Compile Include="Services\Specification\BaseSpecification.cs" />
<Compile Include="Services\Specification\Building\ISpecificationBuilder.cs" />
<Compile Include="Services\Specification\Building\ISpecificationConstructor.cs" />
<Compile Include="Services\Specification\Building\SpecificationConstructorParameterKind.cs" />
<Compile Include="Services\Specification\Building\SpecificationConstructorParametersResolver.cs" />
<Compile Include="Services\Specification\Building\SpecificationParameter.cs" />
<Compile Include="Services\Specification\CurrySpecification.cs" />
<Compile Include="Services\Specification\ExpressionSpecification.cs" />
<Compile Include="Services\Specification\ISpecification.cs" />
<Compile Include="Services\Specification\ISpecificationFinder.cs" />
<Compile Include="Services\Specification\NotSpecification.cs" />
<Compile Include="Services\Specification\OrSpecification.cs" />
<Compile Include="Services\Specification\PredicateBuilder.cs" />
<Compile Include="Services\Specification\Services\AssemblySpecificationFactory.cs" />
<Compile Include="Services\Specification\Services\SpecificationBuilder.cs" />
<Compile Include="Services\Specification\Services\SpecificationConstructor.cs" />
<Compile Include="Services\Specification\Specification.cs" />
<Compile Include="Services\Specification\SpecificationReader.cs" />
<Compile Include="Services\Specification\TrueSpecification.cs" />
<Compile Include="Services\Text\PlainTextTables\TextTableData.cs" />
<Compile Include="Services\Text\PlainTextTables\TextTableRender.cs" />
<Compile Include="Services\Text\PlainTextTables\TextTableRenderOptions.cs" />
<Compile Include="Services\Text\PlainTextTables\TextTableStyle.cs" />
<Compile Include="Services\Text\TStringReader.cs" />
<Compile Include="Services\Trees\Contracts\ITree.cs" />
<Compile Include="Services\Trees\Contracts\ITreeNode.cs" />
<Compile Include="Services\Trees\Generic.cs" />
<Compile Include="Services\Trees\Tree.cs" />
<Compile Include="Services\Trees\TreeNode.cs" />
<Compile Include="Services\Trees\TreesVisitor.cs" />
<Compile Include="Services\Web\HtmlUtility.cs" />
<Compile Include="Services\Web\UrlUtility.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Services\Semantic\Contracts\README.txt" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
Loading…
Cancel
Save

Powered by TurnKey Linux.