From 4d556fbe1013634579202dc8e30c2b5dbeb55290 Mon Sep 17 00:00:00 2001 From: "a.bozhenov" Date: Mon, 29 Apr 2019 22:21:32 +0300 Subject: [PATCH] Move to .net standart --- ZeroLevel.Discovery/App.config | 22 - .../Controllers/BaseController.cs | 97 ----- .../HttpRequestMessagesExtensions.cs | 72 ---- .../Controllers/RoutesController.cs | 37 -- ZeroLevel.Discovery/DiscoveryService.cs | 52 --- ZeroLevel.Discovery/Program.cs | 11 - .../Properties/AssemblyInfo.cs | 35 -- ZeroLevel.Discovery/RouteTable.cs | 222 ---------- ZeroLevel.Discovery/Startup.cs | 80 ---- .../ZeroLevel.Discovery.csproj | 96 ----- ...le_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs | 0 ...le_5937a670-0e60-4077-877b-f7221da3dda1.cs | 0 ...le_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs | 0 ...l.Discovery.csproj.CoreCompileInputs.cache | 1 - ...el.Discovery.csprojAssemblyReference.cache | Bin 160996 -> 0 bytes ZeroLevel.Discovery/packages.config | 12 - ZeroLevel.UnitTests/ArrayToolsTest.cs | 29 +- ZeroLevel.UnitTests/CollectionsTests.cs | 107 ++--- ZeroLevel.UnitTests/EncryptionTests.cs | 25 +- ZeroLevel.UnitTests/ExchangeTests.cs | 21 +- ZeroLevel.UnitTests/InvokingTest.cs | 84 ++-- ZeroLevel.UnitTests/MappingTest.cs | 172 ++++---- ZeroLevel.UnitTests/PredicateBuilderTests.cs | 69 ++-- .../Properties/AssemblyInfo.cs | 20 - ZeroLevel.UnitTests/QueriesTests.cs | 59 ++- ZeroLevel.UnitTests/ReflectionTests.cs | 39 -- ZeroLevel.UnitTests/SerializationTests.cs | 69 ++-- .../SpecificationPatternTest.cs | 213 +++++----- .../ZeroLevel.UnitTests.csproj | 106 +---- ZeroLevel.UnitTests/packages.config | 5 - ZeroLevel.sln | 56 +-- ZeroLevel/Models/BinaryDocument.cs | 133 ------ ZeroLevel/Properties/AssemblyInfo.cs | 35 -- .../Application/BaseWindowsService.cs | 133 ------ .../Application/BasicServiceInstaller.cs | 114 ------ ZeroLevel/Services/Application/Bootstrap.cs | 168 -------- .../Services/Application/IZeroService.cs | 21 - ...xService.cs => BaseZeroExchangeService.cs} | 11 +- ZeroLevel/Services/BaseZeroService.cs | 69 ++++ ZeroLevel/Services/Bootstrap.cs | 111 +++++ .../Services/Diagnostics/StackTraceReader.cs | 36 -- ZeroLevel/Services/Drawing/TextPainter.cs | 76 ---- ZeroLevel/Services/FileSystem/FSUtils.cs | 18 - ZeroLevel/Services/FileSystem/FileArchive.cs | 22 +- .../FileSystem/PeriodicFileSystemWatcher.cs | 2 - ZeroLevel/Services/IZeroService.cs | 13 + .../Impersonation/IImpersonationExecutor.cs | 14 - .../Services/Impersonation/Impersonation.cs | 149 ------- .../ImpersonationNativeMethods.cs | 198 --------- .../Impersonation/MySafeTokenHandle.cs | 26 -- .../ProcessImpersonationExecutor.cs | 70 ---- .../UserImpersonationExecutor.cs | 48 --- .../Logging/Implementation/TextFileLogger.cs | 4 - .../Services/Reflection/DTOTypeBuilder.cs | 151 ------- .../Services/Reflection/ReferenceHelper.cs | 25 -- .../Services/Reflection/TypeActivator.cs | 125 ------ .../{Application => }/ZeroServiceState.cs | 5 +- ZeroLevel/Startup.cs | 56 --- ZeroLevel/ZeroLevel.csproj | 386 +----------------- 59 files changed, 629 insertions(+), 3401 deletions(-) delete mode 100644 ZeroLevel.Discovery/App.config delete mode 100644 ZeroLevel.Discovery/Controllers/BaseController.cs delete mode 100644 ZeroLevel.Discovery/Controllers/HttpRequestMessagesExtensions.cs delete mode 100644 ZeroLevel.Discovery/Controllers/RoutesController.cs delete mode 100644 ZeroLevel.Discovery/DiscoveryService.cs delete mode 100644 ZeroLevel.Discovery/Program.cs delete mode 100644 ZeroLevel.Discovery/Properties/AssemblyInfo.cs delete mode 100644 ZeroLevel.Discovery/RouteTable.cs delete mode 100644 ZeroLevel.Discovery/Startup.cs delete mode 100644 ZeroLevel.Discovery/ZeroLevel.Discovery.csproj delete mode 100644 ZeroLevel.Discovery/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs delete mode 100644 ZeroLevel.Discovery/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs delete mode 100644 ZeroLevel.Discovery/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs delete mode 100644 ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache delete mode 100644 ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache delete mode 100644 ZeroLevel.Discovery/packages.config delete mode 100644 ZeroLevel.UnitTests/Properties/AssemblyInfo.cs delete mode 100644 ZeroLevel.UnitTests/ReflectionTests.cs delete mode 100644 ZeroLevel.UnitTests/packages.config delete mode 100644 ZeroLevel/Models/BinaryDocument.cs delete mode 100644 ZeroLevel/Properties/AssemblyInfo.cs delete mode 100644 ZeroLevel/Services/Application/BaseWindowsService.cs delete mode 100644 ZeroLevel/Services/Application/BasicServiceInstaller.cs delete mode 100644 ZeroLevel/Services/Application/Bootstrap.cs delete mode 100644 ZeroLevel/Services/Application/IZeroService.cs rename ZeroLevel/Services/{Application/BaseWindowsExService.cs => BaseZeroExchangeService.cs} (92%) create mode 100644 ZeroLevel/Services/BaseZeroService.cs create mode 100644 ZeroLevel/Services/Bootstrap.cs delete mode 100644 ZeroLevel/Services/Diagnostics/StackTraceReader.cs delete mode 100644 ZeroLevel/Services/Drawing/TextPainter.cs create mode 100644 ZeroLevel/Services/IZeroService.cs delete mode 100644 ZeroLevel/Services/Impersonation/IImpersonationExecutor.cs delete mode 100644 ZeroLevel/Services/Impersonation/Impersonation.cs delete mode 100644 ZeroLevel/Services/Impersonation/ImpersonationNativeMethods.cs delete mode 100644 ZeroLevel/Services/Impersonation/MySafeTokenHandle.cs delete mode 100644 ZeroLevel/Services/Impersonation/ProcessImpersonationExecutor.cs delete mode 100644 ZeroLevel/Services/Impersonation/UserImpersonationExecutor.cs delete mode 100644 ZeroLevel/Services/Reflection/DTOTypeBuilder.cs delete mode 100644 ZeroLevel/Services/Reflection/ReferenceHelper.cs delete mode 100644 ZeroLevel/Services/Reflection/TypeActivator.cs rename ZeroLevel/Services/{Application => }/ZeroServiceState.cs (60%) delete mode 100644 ZeroLevel/Startup.cs diff --git a/ZeroLevel.Discovery/App.config b/ZeroLevel.Discovery/App.config deleted file mode 100644 index a2e2e28..0000000 --- a/ZeroLevel.Discovery/App.config +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ZeroLevel.Discovery/Controllers/BaseController.cs b/ZeroLevel.Discovery/Controllers/BaseController.cs deleted file mode 100644 index f10d247..0000000 --- a/ZeroLevel.Discovery/Controllers/BaseController.cs +++ /dev/null @@ -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(HttpRequestMessage request, Func 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 - } -} \ No newline at end of file diff --git a/ZeroLevel.Discovery/Controllers/HttpRequestMessagesExtensions.cs b/ZeroLevel.Discovery/Controllers/HttpRequestMessagesExtensions.cs deleted file mode 100644 index 01a65e2..0000000 --- a/ZeroLevel.Discovery/Controllers/HttpRequestMessagesExtensions.cs +++ /dev/null @@ -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(this HttpRequestMessage request, T val, HttpStatusCode code = HttpStatusCode.OK) - { - var response = request.CreateResponse(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; - } - } -} \ No newline at end of file diff --git a/ZeroLevel.Discovery/Controllers/RoutesController.cs b/ZeroLevel.Discovery/Controllers/RoutesController.cs deleted file mode 100644 index 798ff2b..0000000 --- a/ZeroLevel.Discovery/Controllers/RoutesController.cs +++ /dev/null @@ -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))] - public HttpResponseMessage GetRoutes(HttpRequestMessage request) - { - try - { - return request.CreateSelfDestroyingResponse(Injector.Default.Resolve().Get()); - } - catch (Exception ex) - { - Log.Error(ex, "Error with read records"); - return BadRequestAnswer(request, ex); - } - } - } -} \ No newline at end of file diff --git a/ZeroLevel.Discovery/DiscoveryService.cs b/ZeroLevel.Discovery/DiscoveryService.cs deleted file mode 100644 index a0ce469..0000000 --- a/ZeroLevel.Discovery/DiscoveryService.cs +++ /dev/null @@ -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); - var port = Configuration.Default.First("apiport"); - Startup.StartWebPanel(port, false); - - var socketPort = Configuration.Default.First("socketport"); - _exInbox = ExchangeTransportFactory.GetServer(socketPort); - _exInbox.RegisterInbox>("services", (_, __) => routeTable.Get()); - _exInbox.RegisterInbox("register", (info, _, client) => routeTable.Append(info, client)); - - Log.Info($"TCP server started {_exInbox.Endpoint.Address}:{socketPort}"); - } - - public override void StopAction() - { - _exInbox.Dispose(); - } - } -} \ No newline at end of file diff --git a/ZeroLevel.Discovery/Program.cs b/ZeroLevel.Discovery/Program.cs deleted file mode 100644 index e6df01f..0000000 --- a/ZeroLevel.Discovery/Program.cs +++ /dev/null @@ -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(args); - } - } -} \ No newline at end of file diff --git a/ZeroLevel.Discovery/Properties/AssemblyInfo.cs b/ZeroLevel.Discovery/Properties/AssemblyInfo.cs deleted file mode 100644 index 72ecdc1..0000000 --- a/ZeroLevel.Discovery/Properties/AssemblyInfo.cs +++ /dev/null @@ -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")] \ No newline at end of file diff --git a/ZeroLevel.Discovery/RouteTable.cs b/ZeroLevel.Discovery/RouteTable.cs deleted file mode 100644 index 662efeb..0000000 --- a/ZeroLevel.Discovery/RouteTable.cs +++ /dev/null @@ -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 _table = new Dictionary(); - 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>(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>(); - _lock.EnterReadLock(); - try - { - foreach (var pair in _table) - { - var endpointsToRemove = new List(); - 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()); - } - 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() - }); - _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 Get() - { - _lock.EnterReadLock(); - try - { - return _table.Values.ToList(); - } - finally - { - _lock.ExitReadLock(); - } - } - - public void Dispose() - { - _lock.Dispose(); - } - } -} \ No newline at end of file diff --git a/ZeroLevel.Discovery/Startup.cs b/ZeroLevel.Discovery/Startup.cs deleted file mode 100644 index a2df70b..0000000 --- a/ZeroLevel.Discovery/Startup.cs +++ /dev/null @@ -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 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 GetActionRouteFactories(HttpActionDescriptor actionDescriptor) - { - // inherit route attributes decorated on base class controller's actions - return actionDescriptor.GetCustomAttributes(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(url: baseAddress); - Log.Info(string.Format("Web panel url: {0}", baseAddress)); - } - } -} \ No newline at end of file diff --git a/ZeroLevel.Discovery/ZeroLevel.Discovery.csproj b/ZeroLevel.Discovery/ZeroLevel.Discovery.csproj deleted file mode 100644 index 1770242..0000000 --- a/ZeroLevel.Discovery/ZeroLevel.Discovery.csproj +++ /dev/null @@ -1,96 +0,0 @@ - - - - - Debug - AnyCPU - {4F55B23F-938C-4DA2-B6DC-B6BC66D36073} - Exe - ZeroLevel.Discovery - ZeroLevel.Discovery - v4.7.2 - 512 - true - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\packages\Microsoft.Owin.4.0.1\lib\net45\Microsoft.Owin.dll - - - ..\packages\Microsoft.Owin.Host.HttpListener.4.0.1\lib\net45\Microsoft.Owin.Host.HttpListener.dll - - - ..\packages\Microsoft.Owin.Hosting.4.0.1\lib\net45\Microsoft.Owin.Hosting.dll - - - ..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll - - - ..\packages\Owin.1.0\lib\net40\Owin.dll - - - - - ..\packages\Microsoft.AspNet.WebApi.Client.5.2.7\lib\net45\System.Net.Http.Formatting.dll - - - - ..\packages\Microsoft.AspNet.WebApi.Core.5.2.7\lib\net45\System.Web.Http.dll - - - ..\packages\Microsoft.AspNet.WebApi.Owin.5.2.7\lib\net45\System.Web.Http.Owin.dll - - - ..\packages\Microsoft.AspNet.WebApi.SelfHost.5.2.7\lib\net45\System.Web.Http.SelfHost.dll - - - - - - - - - - - - - - Component - - - - - - - - - - - - - {37020d8d-34e8-4ec3-a447-8396d5080457} - ZeroLevel - - - - \ No newline at end of file diff --git a/ZeroLevel.Discovery/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs b/ZeroLevel.Discovery/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs deleted file mode 100644 index e69de29..0000000 diff --git a/ZeroLevel.Discovery/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs b/ZeroLevel.Discovery/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs deleted file mode 100644 index e69de29..0000000 diff --git a/ZeroLevel.Discovery/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs b/ZeroLevel.Discovery/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs deleted file mode 100644 index e69de29..0000000 diff --git a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache b/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache deleted file mode 100644 index 1075f0e..0000000 --- a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csproj.CoreCompileInputs.cache +++ /dev/null @@ -1 +0,0 @@ -44c25bb53ca989abffacb949ad26248970e4d0d4 diff --git a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache b/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache deleted file mode 100644 index 1da12914763c53e2808c41590ec7555264e1c19a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 160996 zcmeI52Y3`k8^^POyJSNNK~PXZ_(V}kLg=8>P?cT>1<+o@wq&O=-kbSm)`iRhEf3Qndt2Vjqay#Uvr{}b5R6hbG{FqyZscP9I-(Bot1Fg(op1R8Z&(`@^+JG$WMb9}*5t4dnR4iR3UmFvDLJ zAu95Y^5qx%i{j#{REhI=swJwf)!)`?qVRKnrvL5Gj@|l^uad^VnpMeoU~18~bo}>v zVS>FnXATJmrXprC$NIye%tBxGWM7`YD6=#s2TuzGQ~QOABB}i%k-`B1#AVPQPHl^H zO3%y>WMu~Zk+$v1KOrYS-%If{_E4@F2<9EkmFO_iPlW!M)Kpb4dK487@<&of`?Go! z22wNf1O8wnwOwlK)DBW0Vo^&6Qead2gu(^BNW_*mA)j8>`xI{j{8Rn;nOT8gW-otM zah?^ImYe0PB%Bt=pqLKjg?$B$`hdTpMyH+MvHj_p!~D7aus@jXZ`7lx$X@`)<;c(M zgX8_vLgC4ose^itDE&3HZEA5Qr44>o+7h0FAhRe+{aJ`X5$X1!5yihUx70NC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tHacg{xd_ey~uZ2^%A^jJux4}MV!{K^FA zQGZH-Ka>J{nE*Y{O({T+ZQ~r!gSwolKu_&b3edy3xBxwV$r2EeNY7#-0Tzk$$R#d7 zkJ)khfS$Rd^Z`9uM+k@_jUK4t6riW8C`y*mYH1-w##7P@l*TF`6>h`d0no0S5zh?xt}QdOq_ty@(Jv{wqydPHXs zXmO%afYu;#AJ8&0rw?e&nNon3mT>`EPUQ3ftu0at&=MjpKublOKA?3YN P!UbqS dfYS%GIzTBvivXB_K^276;4^4`vh}Un{{fM-u|EI+ diff --git a/ZeroLevel.Discovery/packages.config b/ZeroLevel.Discovery/packages.config deleted file mode 100644 index 584a933..0000000 --- a/ZeroLevel.Discovery/packages.config +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/ZeroLevel.UnitTests/ArrayToolsTest.cs b/ZeroLevel.UnitTests/ArrayToolsTest.cs index fd21dd6..54f28ca 100644 --- a/ZeroLevel.UnitTests/ArrayToolsTest.cs +++ b/ZeroLevel.UnitTests/ArrayToolsTest.cs @@ -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)); } } } diff --git a/ZeroLevel.UnitTests/CollectionsTests.cs b/ZeroLevel.UnitTests/CollectionsTests.cs index 16e68fa..2f74634 100644 --- a/ZeroLevel.UnitTests/CollectionsTests.cs +++ b/ZeroLevel.UnitTests/CollectionsTests.cs @@ -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("Title"); - typeBuilder.AppendProperty("Id"); - typeBuilder.AppendProperty("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("id", "stringidentity"); - storage.Add("id", 123); - storage.Add("id", 234); - storage.Add(type, "rt", instance); - - // Assert - Assert.IsTrue(storage.ContainsKey("id")); - Assert.IsTrue(storage.ContainsKey("id")); - Assert.IsTrue(storage.ContainsKey("id")); - Assert.IsTrue(storage.ContainsKey(type, "rt")); - Assert.IsFalse(storage.ContainsKey("somekey")); - Assert.IsFalse(storage.ContainsKey("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("id"), (long)123); - Assert.AreEqual(storage.Get("id"), 234); - Assert.AreEqual(storage.Get("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 })); } } } diff --git a/ZeroLevel.UnitTests/EncryptionTests.cs b/ZeroLevel.UnitTests/EncryptionTests.cs index 3021c39..653fd6e 100644 --- a/ZeroLevel.UnitTests/EncryptionTests.cs +++ b/ZeroLevel.UnitTests/EncryptionTests.cs @@ -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(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(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)); } } } diff --git a/ZeroLevel.UnitTests/ExchangeTests.cs b/ZeroLevel.UnitTests/ExchangeTests.cs index 3b9a861..f5f6425 100644 --- a/ZeroLevel.UnitTests/ExchangeTests.cs +++ b/ZeroLevel.UnitTests/ExchangeTests.cs @@ -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(); diff --git a/ZeroLevel.UnitTests/InvokingTest.cs b/ZeroLevel.UnitTests/InvokingTest.cs index 4b170a6..e6b1f96 100644 --- a/ZeroLevel.UnitTests/InvokingTest.cs +++ b/ZeroLevel.UnitTests/InvokingTest.cs @@ -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(m => m.Name.Equals("GetHelp") || m.Name.Equals("GetNumber")); + invoker.Configure(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"); + var date = DateTime.Now; + 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(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" })); } } } diff --git a/ZeroLevel.UnitTests/MappingTest.cs b/ZeroLevel.UnitTests/MappingTest.cs index 4bd142b..782b5bc 100644 --- a/ZeroLevel.UnitTests/MappingTest.cs +++ b/ZeroLevel.UnitTests/MappingTest.cs @@ -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(); 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(); 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)); + 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)); } - [TestMethod] + [Fact] public void TestAbstractClassMapping() { // Arrange @@ -94,24 +93,25 @@ namespace ZeroMappingTest mapper.Set(instance, "Title", title); mapper.Set(instance, "Description", description); // Assert - Assert.AreEqual(mapper.Get(instance, "Id"), id); - Assert.AreEqual(mapper.Get(instance, "Title"), title); - Assert.AreEqual(mapper.Get(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.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(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.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(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); + + 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(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); } } } diff --git a/ZeroLevel.UnitTests/PredicateBuilderTests.cs b/ZeroLevel.UnitTests/PredicateBuilderTests.cs index 642c7d0..284fe76 100644 --- a/ZeroLevel.UnitTests/PredicateBuilderTests.cs +++ b/ZeroLevel.UnitTests/PredicateBuilderTests.cs @@ -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)); } } } diff --git a/ZeroLevel.UnitTests/Properties/AssemblyInfo.cs b/ZeroLevel.UnitTests/Properties/AssemblyInfo.cs deleted file mode 100644 index fb56531..0000000 --- a/ZeroLevel.UnitTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -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")] diff --git a/ZeroLevel.UnitTests/QueriesTests.cs b/ZeroLevel.UnitTests/QueriesTests.cs index 4d3c86f..a2d7540 100644 --- a/ZeroLevel.UnitTests/QueriesTests.cs +++ b/ZeroLevel.UnitTests/QueriesTests.cs @@ -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 description for UnitTest1 /// - [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(); @@ -57,15 +56,15 @@ namespace ZeroSpecificationPatternsTest Summary = "Summary #3", Title = "Title #3" }); - Assert.IsTrue(a1.Success); - Assert.AreEqual(a1.Count, 1); - Assert.IsTrue(a2.Success); - Assert.AreEqual(a2.Count, 1); - Assert.IsTrue(a3.Success); - Assert.AreEqual(a3.Count, 1); + Assert.True(a1.Success); + Assert.Equal(a1.Count, 1); + Assert.True(a2.Success); + Assert.Equal(a2.Count, 1); + Assert.True(a3.Success); + Assert.Equal(a3.Count, 1); } - [TestMethod] + [Fact] public void MemoryStorageGetAllTest() { var set = new List(); @@ -100,13 +99,13 @@ namespace ZeroSpecificationPatternsTest foreach (var i in set) { var ar = storage.Post(i); - Assert.IsTrue(ar.Success); - Assert.AreEqual(ar.Count, 1); + Assert.True(ar.Success); + Assert.Equal(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(); @@ -156,35 +155,35 @@ namespace ZeroSpecificationPatternsTest foreach (var i in set) { var ar = storage.Post(i); - Assert.IsTrue(ar.Success); - Assert.AreEqual(ar.Count, 1); + Assert.True(ar.Success); + Assert.Equal(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(result_eq.Count(), 1); - Assert.IsTrue(TestDTOEqual(set[0], result_eq.First())); + Assert.Equal(result_eq.Count(), 1); + Assert.True(TestDTOEqual(set[0], result_eq.First())); var result_neq = storage.Get(Query.NEQ("Title", "Title #1")); - Assert.AreEqual(result_neq.Count(), 2); - Assert.IsTrue(TestDTOEqual(set[1], result_neq.First())); - Assert.IsTrue(TestDTOEqual(set[2], result_neq.Skip(1).First())); + Assert.Equal(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(result_gt.Count(), 2); - Assert.IsTrue(TestDTOEqual(set[0], result_gt.First())); - Assert.IsTrue(TestDTOEqual(set[2], result_gt.Skip(1).First())); + Assert.Equal(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(result_lt.Count(), 1); - Assert.IsTrue(TestDTOEqual(set[1], result_lt.First())); + Assert.Equal(result_lt.Count(), 1); + Assert.True(TestDTOEqual(set[1], result_lt.First())); } } } diff --git a/ZeroLevel.UnitTests/ReflectionTests.cs b/ZeroLevel.UnitTests/ReflectionTests.cs deleted file mode 100644 index 8bfa194..0000000 --- a/ZeroLevel.UnitTests/ReflectionTests.cs +++ /dev/null @@ -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("Title"); - typeBuilder.AppendProperty("Id"); - typeBuilder.AppendProperty("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"); - } - } -} diff --git a/ZeroLevel.UnitTests/SerializationTests.cs b/ZeroLevel.UnitTests/SerializationTests.cs index caa4fd1..70b9730 100644 --- a/ZeroLevel.UnitTests/SerializationTests.cs +++ b/ZeroLevel.UnitTests/SerializationTests.cs @@ -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(IEnumerable A, IEnumerable B, Func comparer) @@ -38,11 +37,11 @@ namespace ZeroLevel.UnitTests // Assert if (comparator == null) { - Assert.AreEqual(value, clone); + Assert.Equal(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.Now); @@ -75,7 +74,7 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(DateTime.MaxValue); } - [TestMethod] + [Fact] public void SerializeIPAddress() { var comparator = new Func((left, right) => NetUtils.Compare(left, right) == 0); @@ -89,7 +88,7 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(IPAddress.Parse("93.111.16.58"), comparator); } - [TestMethod] + [Fact] public void SerializeIPEndPoint() { var comparator = new Func((left, right) => NetUtils.Compare(left, right) == 0); @@ -103,14 +102,14 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(new IPEndPoint(IPAddress.Parse("93.111.16.58"), IPEndPoint.MinPort), comparator); } - [TestMethod] + [Fact] public void SerializeGuid() { MakePrimitiveTest(Guid.Empty); MakePrimitiveTest(Guid.NewGuid()); } - [TestMethod] + [Fact] public void SerializeTimeSpan() { MakePrimitiveTest(TimeSpan.MaxValue); @@ -122,7 +121,7 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(TimeSpan.FromTicks(0)); } - [TestMethod] + [Fact] public void SerializeString() { var comparator = new Func((left, right) => @@ -137,7 +136,7 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest("𐌼𐌰𐌲 𐌲𐌻𐌴𐍃 𐌹̈𐍄𐌰𐌽, 𐌽𐌹 𐌼𐌹𐍃 𐍅𐌿 𐌽𐌳𐌰𐌽 𐌱𐍂𐌹𐌲𐌲𐌹𐌸", comparator); } - [TestMethod] + [Fact] public void SerializeInt32() { MakePrimitiveTest(-0); @@ -148,7 +147,7 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(Int32.MaxValue); } - [TestMethod] + [Fact] public void SerializeInt64() { MakePrimitiveTest(-0); @@ -161,7 +160,7 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(Int64.MaxValue / 2); } - [TestMethod] + [Fact] public void SerializeDecimal() { MakePrimitiveTest(-0); @@ -174,7 +173,7 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(Decimal.MaxValue / 2); } - [TestMethod] + [Fact] public void SerializeFloat() { MakePrimitiveTest(-0); @@ -187,7 +186,7 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(float.MaxValue / 2); } - [TestMethod] + [Fact] public void SerializeDouble() { MakePrimitiveTest(-0); @@ -200,14 +199,14 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(Double.MaxValue / 2); } - [TestMethod] + [Fact] public void SerializeBoolean() { MakePrimitiveTest(true); MakePrimitiveTest(false); } - [TestMethod] + [Fact] public void SerializeByte() { MakePrimitiveTest(0); @@ -218,7 +217,7 @@ namespace ZeroLevel.UnitTests MakePrimitiveTest(255); } - [TestMethod] + [Fact] public void SerializeBytes() { var comparator = new Func((left, right) => @@ -233,7 +232,7 @@ namespace ZeroLevel.UnitTests COLLECTIONS */ - [TestMethod] + [Fact] public void SerializeCollectionDateTime() { MakeCollectionTest(null); @@ -241,7 +240,7 @@ namespace ZeroLevel.UnitTests MakeCollectionTest(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((left, right) => NetUtils.Compare(left, right) == 0); @@ -249,7 +248,7 @@ namespace ZeroLevel.UnitTests MakeCollectionTest(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((left, right) => NetUtils.Compare(left, right) == 0); @@ -258,7 +257,7 @@ namespace ZeroLevel.UnitTests MakeCollectionTest(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(null); @@ -266,13 +265,13 @@ namespace ZeroLevel.UnitTests MakeCollectionTest(new Guid[] { Guid.Empty, Guid.NewGuid() }); } - [TestMethod] + [Fact] public void SerializeCollectionTimeSpan() { MakeCollectionTest(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((left, right) => @@ -284,49 +283,49 @@ namespace ZeroLevel.UnitTests } - [TestMethod] + [Fact] public void SerializeCollectionInt32() { MakeCollectionTest(new int[] { -0, 0, -10, 10, Int32.MinValue, Int32.MaxValue }); } - [TestMethod] + [Fact] public void SerializeCollectionInt64() { MakeCollectionTest(new long[] { -0, 0, -10, 10, Int64.MinValue, Int64.MaxValue, Int64.MinValue / 2, Int64.MaxValue / 2 }); } - [TestMethod] + [Fact] public void SerializeCollectionDecimal() { MakeCollectionTest(new Decimal[] { -0, 0, -10, 10, Decimal.MinValue, Decimal.MaxValue, Decimal.MinValue / 2, Decimal.MaxValue / 2 }); } - [TestMethod] + [Fact] public void SerializeCollectionFloat() { MakeCollectionTest(new float[] { -0, 0, -10, 10, float.MinValue, float.MaxValue, float.MinValue / 2, float.MaxValue / 2 }); } - [TestMethod] + [Fact] public void SerializeCollectionDouble() { MakeCollectionTest(new Double[] { -0, 0, -10, 10, Double.MinValue, Double.MaxValue, Double.MinValue / 2, Double.MaxValue / 2 }); } - [TestMethod] + [Fact] public void SerializeCollectionBoolean() { MakeCollectionTest(new Boolean[] { true, false, true }); } - [TestMethod] + [Fact] public void SerializeCollectionByte() { MakeCollectionTest(new byte[] { 0, 3, -0, 1, 10, 128, 255 }); } - [TestMethod] + [Fact] public void SerializeCollectionBytes() { var comparator = new Func((left, right) => @@ -335,7 +334,7 @@ namespace ZeroLevel.UnitTests MakeCollectionTest(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((left, right) => diff --git a/ZeroLevel.UnitTests/SpecificationPatternTest.cs b/ZeroLevel.UnitTests/SpecificationPatternTest.cs index 17f84a9..746d7eb 100644 --- a/ZeroLevel.UnitTests/SpecificationPatternTest.cs +++ b/ZeroLevel.UnitTests/SpecificationPatternTest.cs @@ -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 description for SpecificationPatternTest /// - [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(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)); } } } diff --git a/ZeroLevel.UnitTests/ZeroLevel.UnitTests.csproj b/ZeroLevel.UnitTests/ZeroLevel.UnitTests.csproj index 9bd29d6..9a1dc8d 100644 --- a/ZeroLevel.UnitTests/ZeroLevel.UnitTests.csproj +++ b/ZeroLevel.UnitTests/ZeroLevel.UnitTests.csproj @@ -1,99 +1,19 @@ - - - - + + - Debug - AnyCPU - {C500B489-C432-499D-B0E4-B41998B12C49} - Library - Properties - ZeroLevel.UnitTests - ZeroLevel.UnitTests - v4.7.2 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 15.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages - False - UnitTest - - + netcoreapp2.2 + + false - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll - - - ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + + + + - - {37020d8d-34e8-4ec3-a447-8396d5080457} - ZeroLevel - + - - - - - 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}. - - - - - - \ No newline at end of file + + diff --git a/ZeroLevel.UnitTests/packages.config b/ZeroLevel.UnitTests/packages.config deleted file mode 100644 index 2f7c5a1..0000000 --- a/ZeroLevel.UnitTests/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/ZeroLevel.sln b/ZeroLevel.sln index e434381..6fc4804 100644 --- a/ZeroLevel.sln +++ b/ZeroLevel.sln @@ -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 diff --git a/ZeroLevel/Models/BinaryDocument.cs b/ZeroLevel/Models/BinaryDocument.cs deleted file mode 100644 index 39916c7..0000000 --- a/ZeroLevel/Models/BinaryDocument.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System; -using System.Collections.Generic; -using ZeroLevel.DocumentObjectModel; -using ZeroLevel.Services.Serialization; - -namespace ZeroLevel.Models -{ - /// - /// Binary data represantation - /// - public class BinaryDocument : - IBinarySerializable, - IEquatable, - ICloneable - { - /// - /// Id - /// - public Guid Id { get; set; } - - /// - /// File name - /// - public string FileName { get; set; } - - /// - /// Content type (pdf, doc, etc.) - /// - public string ContentType { get; set; } - - /// - /// Content - /// - public byte[] Document { get; set; } - - /// - /// Creation date - /// - public DateTime Created { get; set; } - - /// - /// Optional headers - /// - public List
Headers { get; set; } - - /// - /// Categories - /// - public List Categories { get; set; } - - #region Ctors - - public BinaryDocument() - { - Created = DateTime.Now; - Headers = new List
(); - Categories = new List(); - } - - 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
(); - this.Categories = reader.ReadCollection(); - } - - #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); - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Properties/AssemblyInfo.cs b/ZeroLevel/Properties/AssemblyInfo.cs deleted file mode 100644 index 5aa011f..0000000 --- a/ZeroLevel/Properties/AssemblyInfo.cs +++ /dev/null @@ -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")] \ No newline at end of file diff --git a/ZeroLevel/Services/Application/BaseWindowsService.cs b/ZeroLevel/Services/Application/BaseWindowsService.cs deleted file mode 100644 index 2572f5f..0000000 --- a/ZeroLevel/Services/Application/BaseWindowsService.cs +++ /dev/null @@ -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 - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Application/BasicServiceInstaller.cs b/ZeroLevel/Services/Application/BasicServiceInstaller.cs deleted file mode 100644 index a7ae072..0000000 --- a/ZeroLevel/Services/Application/BasicServiceInstaller.cs +++ /dev/null @@ -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; - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Application/Bootstrap.cs b/ZeroLevel/Services/Application/Bootstrap.cs deleted file mode 100644 index 70d8739..0000000 --- a/ZeroLevel/Services/Application/Bootstrap.cs +++ /dev/null @@ -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; - } - - /// - /// Self-install as windows service - /// - 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"); - } - } - - /// - /// Uninstall from windows services - /// - 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(string[] args, Func preStartConfiguration = null, Func 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"); } - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Application/IZeroService.cs b/ZeroLevel/Services/Application/IZeroService.cs deleted file mode 100644 index 2b077e3..0000000 --- a/ZeroLevel/Services/Application/IZeroService.cs +++ /dev/null @@ -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(); - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Application/BaseWindowsExService.cs b/ZeroLevel/Services/BaseZeroExchangeService.cs similarity index 92% rename from ZeroLevel/Services/Application/BaseWindowsExService.cs rename to ZeroLevel/Services/BaseZeroExchangeService.cs index 9285643..d6727bd 100644 --- a/ZeroLevel/Services/Application/BaseWindowsExService.cs +++ b/ZeroLevel/Services/BaseZeroExchangeService.cs @@ -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(); } diff --git a/ZeroLevel/Services/BaseZeroService.cs b/ZeroLevel/Services/BaseZeroService.cs new file mode 100644 index 0000000..0a5c911 --- /dev/null +++ b/ZeroLevel/Services/BaseZeroService.cs @@ -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(); + } + } +} \ No newline at end of file diff --git a/ZeroLevel/Services/Bootstrap.cs b/ZeroLevel/Services/Bootstrap.cs new file mode 100644 index 0000000..ac7210a --- /dev/null +++ b/ZeroLevel/Services/Bootstrap.cs @@ -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(string[] args, Func preStartConfiguration = null, Func postStartConfiguration = null) + where T : IZeroService, new() + { + var service = Initialize(args, preStartConfiguration, postStartConfiguration); + if (service != null) + { + service.Start(); + Shutdown(service); + } + } + + private static IZeroService Initialize(string[] args, Func preStartConfiguration = null, Func 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"); } + } + } +} \ No newline at end of file diff --git a/ZeroLevel/Services/Diagnostics/StackTraceReader.cs b/ZeroLevel/Services/Diagnostics/StackTraceReader.cs deleted file mode 100644 index 7466c33..0000000 --- a/ZeroLevel/Services/Diagnostics/StackTraceReader.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; - -namespace ZeroLevel.Services.Diagnostics -{ - /// - /// Performs read of stack trace - /// - public static class StackTraceReader - { - /// - /// Read current stack trace - /// - /// Result - enumerable of tuples as 'Type':'MethodName' - public static Tuple[] ReadFrames() - { - var result = new List>(); - var stackTrace = new StackTrace(); - foreach (var frame in stackTrace.GetFrames() ?? Enumerable.Empty()) - { - 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(type, method.Name)); - } - } - } - return result.ToArray(); - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Drawing/TextPainter.cs b/ZeroLevel/Services/Drawing/TextPainter.cs deleted file mode 100644 index 2a06cb4..0000000 --- a/ZeroLevel/Services/Drawing/TextPainter.cs +++ /dev/null @@ -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 - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/FileSystem/FSUtils.cs b/ZeroLevel/Services/FileSystem/FSUtils.cs index e3282e5..6333b70 100644 --- a/ZeroLevel/Services/FileSystem/FSUtils.cs +++ b/ZeroLevel/Services/FileSystem/FSUtils.cs @@ -41,24 +41,6 @@ namespace ZeroLevel.Services.FileSystem return folderName; } - /// - /// Sets the directory permissions for the account - /// - /// Directory path - /// Account - /// Access rights - /// Access type - public static void SetupFolderPermission(string folderPath, string account, - FileSystemRights right, AccessControlType controlType) - { - 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()); diff --git a/ZeroLevel/Services/FileSystem/FileArchive.cs b/ZeroLevel/Services/FileSystem/FileArchive.cs index bd40eff..dc158c9 100644 --- a/ZeroLevel/Services/FileSystem/FileArchive.cs +++ b/ZeroLevel/Services/FileSystem/FileArchive.cs @@ -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); } } diff --git a/ZeroLevel/Services/FileSystem/PeriodicFileSystemWatcher.cs b/ZeroLevel/Services/FileSystem/PeriodicFileSystemWatcher.cs index ba3aa26..02e3c9f 100644 --- a/ZeroLevel/Services/FileSystem/PeriodicFileSystemWatcher.cs +++ b/ZeroLevel/Services/FileSystem/PeriodicFileSystemWatcher.cs @@ -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))) { diff --git a/ZeroLevel/Services/IZeroService.cs b/ZeroLevel/Services/IZeroService.cs new file mode 100644 index 0000000..1b79ac2 --- /dev/null +++ b/ZeroLevel/Services/IZeroService.cs @@ -0,0 +1,13 @@ +namespace ZeroLevel +{ + public interface IZeroService + { + ZeroServiceState State { get; } + + string Name { get; } + + void Start(); + + void Stop(); + } +} \ No newline at end of file diff --git a/ZeroLevel/Services/Impersonation/IImpersonationExecutor.cs b/ZeroLevel/Services/Impersonation/IImpersonationExecutor.cs deleted file mode 100644 index c57d271..0000000 --- a/ZeroLevel/Services/Impersonation/IImpersonationExecutor.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace ZeroLevel.Services.Impersonation -{ - /// - /// Interface for classes executing code from user or process rights - /// - public interface IImpersonationExecutor - { - void ExecuteCode(Action action, T arg); - - void ExecuteCode(Action action); - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Impersonation/Impersonation.cs b/ZeroLevel/Services/Impersonation/Impersonation.cs deleted file mode 100644 index 63137ef..0000000 --- a/ZeroLevel/Services/Impersonation/Impersonation.cs +++ /dev/null @@ -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 -{ - /// - /// The class implements the translation of the program execution to the rights of the specified user. - /// - [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)] - [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] - public class Impersonation : IDisposable - { - private WindowsImpersonationContext impersonationContext; - - #region Private methods - - /// - /// Assigning rights to the current process from the specified process, by copying its token - /// - /// Process pointer - private void ImpersonateByProcess(IntPtr hProcess) - { - MySafeTokenHandle token; - if (!ImpersonationNativeMethods.OpenProcessToken(hProcess, ImpersonationNativeMethods.TokenDesiredAccess.TOKEN_DUPLICATE, out token)) - throw new ApplicationException("Failed to get the process token. Win32 error code: " + Marshal.GetLastWin32Error()); - ImpersonateToken(token); - } - - /// - /// The method assigns a duplicate token to the current process. - /// - /// Token - private void ImpersonateToken(MySafeTokenHandle token) - { - MySafeTokenHandle tokenDuplicate; - 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 - - /// - /// Login as a specified user - /// - /// User name - /// User domain - /// User password - /// false - if failed to log in with the specified data - public void ImpersonateByUser(String userName, String domain, String password) - { - MySafeTokenHandle token; - 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()); - } - } - - /// - /// Login on behalf of the specified user with the authorization method - /// - /// Login - /// Domain - /// Password - /// Authorization Type - 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()); - } - } - - /// - /// Copying the rights of the specified process - /// - /// Process name - 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; - } - } - } - - /// - /// Copying the rights of the specified process - /// - /// Process id - 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 - - /// - /// When releasing resources, we will return the previous user right - /// - public void Dispose() - { - impersonationContext?.Undo(); - impersonationContext?.Dispose(); - GC.SuppressFinalize(this); - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Impersonation/ImpersonationNativeMethods.cs b/ZeroLevel/Services/Impersonation/ImpersonationNativeMethods.cs deleted file mode 100644 index e7cec40..0000000 --- a/ZeroLevel/Services/Impersonation/ImpersonationNativeMethods.cs +++ /dev/null @@ -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 - - /// - /// Authorization provider - /// - public enum LogonProvider : int - { - /// - /// 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. - /// - LOGON32_PROVIDER_DEFAULT = 0, - } - - /// - /// Authorization method - /// - public enum LogonType : int - { - /// - /// 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. - /// - LOGON32_LOGON_INTERACTIVE = 2, - - /// - /// This logon type is intended for high performance servers to authenticate plaintext passwords. - /// The LogonUser function does not cache credentials for this logon type. - /// - LOGON32_LOGON_NETWORK = 3, - - /// - /// 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. - /// - LOGON32_LOGON_BATCH = 4, - - /// - /// Indicates a service-type logon. The account provided must have the service privilege enabled. - /// - LOGON32_LOGON_SERVICE = 5, - - /// - /// 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. - /// - LOGON32_LOGON_UNLOCK = 7, - - /// - /// 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. - /// - LOGON32_LOGON_NETWORK_CLEARTEXT = 8, - - /// - /// 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. - /// - LOGON32_LOGON_NEW_CREDENTIALS = 9, - } - - /// - /// Desired access level to token - /// - public struct TokenDesiredAccess - { - public static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000; - public static uint STANDARD_RIGHTS_READ = 0x00020000; - public static uint TOKEN_ASSIGN_PRIMARY = 0x0001; - - /// - /// Allows to create a copy - /// - public static uint TOKEN_DUPLICATE = 0x0002; - - public static uint TOKEN_IMPERSONATE = 0x0004; - 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); - } - - /// - /// The security type is used during the token duplication operation (in the current task) - /// - public enum SecurityImpersonationLevel : int - { - /// - /// 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. - /// - SecurityAnonymous = 0, - - /// - /// 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. - /// - SecurityIdentification = 1, - - /// - /// The server process can impersonate the client's security context on its local system. - /// The server cannot impersonate the client on remote systems. - /// - SecurityImpersonation = 2, - - /// - /// The server process can impersonate the client's security context on remote systems. - /// NOTE: Windows NT: This impersonation level is not supported. - /// - SecurityDelegation = 3, - } - - #endregion P/Invoke enums - - #region P/Invoke - - /// - /// Authorization on behalf of the specified user - /// - /// Username - /// Domain - /// Password - /// Authorization Type - /// Provider (always 0) - /// Token - login result - /// - [DllImport("advapi32.dll")] - internal static extern int LogonUserA(String lpszUserName, - String lpszDomain, - String lpszPassword, - int dwLogonType, - int dwLogonProvider, - out MySafeTokenHandle phToken); - - /// - /// Creating a duplicate token - /// - /// Original token - /// - /// - /// - [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); - - /// - /// Attempt to get a token running process - /// - /// Process pointer - /// - /// Token - result - /// - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out MySafeTokenHandle TokenHandle); - - #endregion P/Invoke - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Impersonation/MySafeTokenHandle.cs b/ZeroLevel/Services/Impersonation/MySafeTokenHandle.cs deleted file mode 100644 index 43cacd6..0000000 --- a/ZeroLevel/Services/Impersonation/MySafeTokenHandle.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.Win32.SafeHandles; -using System.Runtime.ConstrainedExecution; -using System.Security.Permissions; - -namespace ZeroLevel.Services.Impersonation -{ - /// - /// Implementing a safe pointer - /// - [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); - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Impersonation/ProcessImpersonationExecutor.cs b/ZeroLevel/Services/Impersonation/ProcessImpersonationExecutor.cs deleted file mode 100644 index 158c758..0000000 --- a/ZeroLevel/Services/Impersonation/ProcessImpersonationExecutor.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; - -namespace ZeroLevel.Services.Impersonation -{ - /// - /// Implements the execution of an code from the rights of the specified process - /// - 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; - } - - /// - /// Code execution - /// - public void ExecuteCode(Action 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); - } - } - - /// - /// Code execution - /// - 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(); - } - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Impersonation/UserImpersonationExecutor.cs b/ZeroLevel/Services/Impersonation/UserImpersonationExecutor.cs deleted file mode 100644 index 3b403cb..0000000 --- a/ZeroLevel/Services/Impersonation/UserImpersonationExecutor.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; - -namespace ZeroLevel.Services.Impersonation -{ - /// - /// Class executing code with the rights of the specified user - /// - 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; - } - - /// - /// Code execution - /// - public void ExecuteCode(Action action, T arg) - { - using (Impersonation imp = new Impersonation()) - { - imp.ImpersonateByUser(USR, DOMAIN, PWD, logonType); - action(arg); - } - } - - /// - /// Code execution - /// - public void ExecuteCode(Action action) - { - using (Impersonation imp = new Impersonation()) - { - imp.ImpersonateByUser(USR, DOMAIN, PWD, logonType); - action(); - } - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Logging/Implementation/TextFileLogger.cs b/ZeroLevel/Services/Logging/Implementation/TextFileLogger.cs index e7a0b20..3f257a5 100644 --- a/ZeroLevel/Services/Logging/Implementation/TextFileLogger.cs +++ b/ZeroLevel/Services/Logging/Implementation/TextFileLogger.cs @@ -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); } } diff --git a/ZeroLevel/Services/Reflection/DTOTypeBuilder.cs b/ZeroLevel/Services/Reflection/DTOTypeBuilder.cs deleted file mode 100644 index 2d0a8cd..0000000 --- a/ZeroLevel/Services/Reflection/DTOTypeBuilder.cs +++ /dev/null @@ -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 -{ - /// - /// Конструктор простейших типов, без методов - /// - public sealed class DTOTypeBuilder - { - #region Fields - private readonly TypeBuilder _typeBuilder; - #endregion - - /// - /// Конструктор - /// - /// Название создаваемого типа - 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(string name) - { - _typeBuilder.DefineField(name, typeof(T), FieldAttributes.Public); - } - - public void AppendField(string name, T defaultValue) - { - var builder = _typeBuilder.DefineField(name, typeof(T), FieldAttributes.Public | FieldAttributes.HasDefault); - builder.SetConstant(defaultValue); - } - - public void AppendProperty(string name) - { - CreateProperty(name, _typeBuilder, null); - } - - public void AppendProperty(string name, T defaultValue) - { - CreateProperty(name, _typeBuilder, null).SetConstant(defaultValue); - } - - public void AppendProperty(string name, string description) - { - CreateProperty(name, _typeBuilder, description); - } - - public void AppendProperty(string name, string description, T defaultValue) - { - CreateProperty(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(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; - } - - /// - /// Собирает конечный тип - /// - /// Готовый тип - public Type Complete() - { - // Сборка типа - var type = _typeBuilder.CreateType(); - // Результат - return type; - } - } -} diff --git a/ZeroLevel/Services/Reflection/ReferenceHelper.cs b/ZeroLevel/Services/Reflection/ReferenceHelper.cs deleted file mode 100644 index 56d6ab2..0000000 --- a/ZeroLevel/Services/Reflection/ReferenceHelper.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Reflection.Emit; - -namespace ZeroLevel.Services.Reflection -{ - public static class ReferenceHelpers - { - public static readonly Action> GetPinnedPtr; - - static ReferenceHelpers() - { - var dyn = new DynamicMethod("GetPinnedPtr", typeof(void), new[] { typeof(object), typeof(Action) }, 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).GetMethod("Invoke")); - il.Emit(OpCodes.Ret); - GetPinnedPtr = (Action>)dyn.CreateDelegate(typeof(Action>)); - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Reflection/TypeActivator.cs b/ZeroLevel/Services/Reflection/TypeActivator.cs deleted file mode 100644 index 37b95c2..0000000 --- a/ZeroLevel/Services/Reflection/TypeActivator.cs +++ /dev/null @@ -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> _withArgumentsConstructorFactories = - new ConcurrentDictionary>(); - - 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(params object[] args) - { - var type = typeof(T); - if (false == _withArgumentsConstructorFactories.ContainsKey(type)) - { - var d = new Dictionary(); - 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() - where T : new() - { - var type = typeof(T); - if (false == _withoutArgumentsConstructorFactories.ContainsKey>(type.FullName)) - { - _withoutArgumentsConstructorFactories.Add>(type.FullName, MakeFactory()); - } - return _withoutArgumentsConstructorFactories. - Get>(type.FullName). - Invoke(); - } - - private static Func MakeFactory() - where T : new() - { - Expression> 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)method.CreateDelegate(typeof(Func)); - } - - private static Tuple 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(identity.ToString(), lambda.Compile()); - } - } -} \ No newline at end of file diff --git a/ZeroLevel/Services/Application/ZeroServiceState.cs b/ZeroLevel/Services/ZeroServiceState.cs similarity index 60% rename from ZeroLevel/Services/Application/ZeroServiceState.cs rename to ZeroLevel/Services/ZeroServiceState.cs index 0be51a6..fdf176d 100644 --- a/ZeroLevel/Services/Application/ZeroServiceState.cs +++ b/ZeroLevel/Services/ZeroServiceState.cs @@ -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 } } \ No newline at end of file diff --git a/ZeroLevel/Startup.cs b/ZeroLevel/Startup.cs deleted file mode 100644 index 92918b9..0000000 --- a/ZeroLevel/Startup.cs +++ /dev/null @@ -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"); - } - } -} diff --git a/ZeroLevel/ZeroLevel.csproj b/ZeroLevel/ZeroLevel.csproj index ad18591..9598bef 100644 --- a/ZeroLevel/ZeroLevel.csproj +++ b/ZeroLevel/ZeroLevel.csproj @@ -1,383 +1,15 @@ - - - + + - Debug - AnyCPU - {37020D8D-34E8-4EC3-A447-8396D5080457} - Library - Properties - ZeroLevel - ZeroLevel - v4.7.2 - 512 - true - + netstandard2.0 - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 + + true - 7.1 - - none - true - bin\Release\ - TRACE - none - 4 + + true - 7.1 - - - - - - - - - - - - - - - - - - - - - - - - Component - - - Component - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + +