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 1da1291..0000000 Binary files a/ZeroLevel.Discovery/obj/Debug/ZeroLevel.Discovery.csprojAssemblyReference.cache and /dev/null differ 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 + +