2
0
mirror of https://github.com/esiur/esiur-dotnet.git synced 2026-03-31 18:38:22 +00:00

comparision test brought here

This commit is contained in:
2026-03-19 15:26:42 +03:00
parent ee3fbd116d
commit e300173bdd
24 changed files with 2613 additions and 424 deletions

View File

@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Esiur.Security.Cryptography\Esiur.Security.Cryptography.csproj" />
<ProjectReference Include="..\..\Esiur\Esiur.csproj" OutputItemType="Analyzer" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,12 @@
using Esiur.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Esiur.Tests.Distribution;
public interface IMyRecord:IRecord
{
}

View File

@@ -0,0 +1,15 @@
using Esiur.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Esiur.Tests.Distribution;
[Export]
public class MyChildRecord : MyRecord
{
public string ChildName { get; set; }
}

View File

@@ -0,0 +1,19 @@
using Esiur.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Esiur.Tests.Distribution;
[Resource]
public partial class MyChildResource : MyResource
{
[Export] string childName;
[Export("Hell2o")] public int ChildMethod(string childName) => 111;
[Export] public new string Hello() => "Hi from Child";
[Export] public string HelloChild() => "Hi from Child";
}

View File

@@ -0,0 +1,18 @@
using Esiur.Data;
using Esiur.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Esiur.Tests.Distribution;
public class MyGenericRecord<T> : IRecord where T : IResource
{
[Export] public int Start { get; set; }
[Export] public int Needed { get; set; }
[Export] public int Total { get; set; }
[Export] public T[] Results { get; set; }
}

View File

@@ -0,0 +1,19 @@
using Esiur.Data;
using Esiur.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Esiur.Tests.Distribution;
[Export]
public class MyRecord:IRecord
{
public string Name { get; set; }
public int Id { get; set; }
public double Score { get; set; }
}

View File

@@ -0,0 +1,31 @@
using Esiur.Core;
using Esiur.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Esiur.Tests.Distribution;
[Resource]
[Annotation("A", "B")]
public partial class MyResource
{
[Export][Annotation("Comment")] string description;
[Export] int categoryId;
[Export] public string Hello() => "Hi";
[Export] public string HelloParent() => "Hi from Parent";
[Export]
[Annotation("This function computes the standard deviation of a list")]
public double StDev(double[] values)
{
double avg = values.Average();
return Math.Sqrt(values.Average(v => Math.Pow(v - avg, 2)));
}
}

View File

@@ -0,0 +1,215 @@
using Esiur.Data;
using Esiur.Core;
using Esiur.Resource;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Esiur.Protocol;
#nullable enable
namespace Esiur.Tests.Distribution;
public enum SizeEnum:short
{
xSmall = -11,
Small,
Medium = 0,
Large,
XLarge = 22
}
[Resource]
public partial class MyService
{
[Export] public event ResourceEventHandler<string>? StringEvent;
[Export] public event ResourceEventHandler<object[]>? ArrayEvent;
[Export] bool boolean = true;
[Export] bool[] booleanArray = new bool[] { true, false, true, false, true };
[Export]
public MyGenericRecord<MyResource> GetGenericRecord()
{
return new MyGenericRecord<MyResource>() { Needed = 3, Start = 10, Results = new MyResource[0], Total = 102 };
}
[Export] public static string staticFunction(string name) => $"Hello {name}";
[Export] byte uInt8Test = 8;
[Export] byte? uInt8Null = null;
[Export] byte[] uInt8Array = new byte[] { 0, 1, 2, 3, 4, 5 };
[Export] byte?[] uInt8ArrayNull = new byte?[] { 0, null, 2, null, 4, null };
[Export] sbyte int8 = -8;
[Export] sbyte[] int8Array = new sbyte[] { -3, -2, -1, 0, 1, 2 };
[Export] char char16 = 'ح';
[Export] char[] char16Array = new char[] { 'م', 'ر', 'ح', 'ب', 'ا' };
[Export] short int16 = -16;
[Export] short[] int16Array = new short[] { -3, -2, -1, 0, 1, 2 };
[Export] ushort uInt16 = 16;
[Export] ushort[] uInt16Array = new ushort[] { 0, 1, 2, 3, 4, 5 };
[Export] int int32Prop = -32;
[Export] int[] int32Array = new int[] { -3, -2, -1, 0, 1, 2 };
[Export] uint uInt32 = 32;
[Export] uint[] uInt32Array = new uint[] { 0, 1, 2, 3, 4, 5 };
[Export] long int64 = 323232323232;
[Export] long[] int64Array = new long[] { -3, -2, -1, 0, 1, 2 };
[Export] ulong uInt64;
[Export] ulong[] uInt64Array = new ulong[] { 0, 1, 2, 3, 4, 5 };
[Export] float float32 = 32.32f;
[Export] float[] float32Array = new float[] { -3.3f, -2.2f, -1.1f, 0, 1.1f, 2.2f };
[Export] double float64 = 32.323232;
[Export] double[] float64Array = new double[] { -3.3, -2.2, -1.1, 0, 1.1, 2.2 };
[Export] decimal float128 = 3232.323232323232m;
[Export] decimal[] float128Array = new decimal[] { -3.3m, -2.2m, -1.1m, 0, 1.1m, 2.2m };
[Export("Text")] string stringTest = "Hello World";
[Export] string[] stringArray = new string[] { "Hello", "World" };
[Export] DateTime time = DateTime.Now;
[Export]
Map<string, object> stringMap = new Map<string, object>()
{
["int"] = 33,
["string"] = "Hello World"
};
[Export]
Map<int, string> intStringMap = new()
{
[4] = "Abcd",
[44] = "EfG"
};
[Export("Object")] object objectTest = "object";
[Export] object[] objectArray = new object[] { 1, 1.2f, Math.PI, "Hello World" };
[Export]
public PropertyContext<int> PropertyContext
{
get => new PropertyContext<int>((sender) => sender.RemoteEndPoint.Port);
set
{
Console.WriteLine($"PropertyContext Set: {value.Value} {value.Connection.RemoteEndPoint.Port}");
}
}
int MyPasscode = 2025;
public PropertyContext<int> Passcode
{
get => new((sender) => sender.Session.AuthorizedAccount == "alice" ? MyPasscode : 0);
set
{
if (value.Connection.Session.AuthorizedAccount != "alice")
throw new Exception("Only Alice is allowed.");
MyPasscode = value.Value;
}
}
[Export] public SizeEnum Enum => SizeEnum.Medium;
[Export] public MyRecord Record => new MyRecord() { Id = 33, Name = "Test", Score = 99.33 };
[Export] public MyRecord? RecordNullable => new MyRecord() { Id = 33, Name = "Test Nullable", Score = 99.33 };
[Export] public List<int> IntList => new List<int>() { 1, 2, 3, 4, 5 };
[Export] public IRecord[] RecordsArray => new IRecord[] { new MyRecord() { Id = 22, Name = "Test", Score = 22.1 } };
[Export] public List<MyRecord> RecordsList => new() { new MyRecord() { Id = 22, Name = "Test", Score = 22.1 } };
[Export] public IMyRecord myrecord { get; set; }
[Export] public MyResource[]? myResources;
[Export] public MyResource? Resource { get; set; }
[Export] public MyChildResource? ChildResource { get; set; }
[Export] MyChildRecord ChildRecord { get; set; } = new MyChildRecord() { ChildName = "Child", Id = 12, Name = "Parent", Score = 12.2 };
[Export] public IResource[]? Resources { get; set; }
[Export]
public void Void() =>
Console.WriteLine("Void()");
[Export]
public void InvokeEvents(string msg, InvocationContext context)
{
//if (context.Connection.Session.AuthorizedAccount != "Alice")
// throw new Exception("Only Alice is allowed.");
StringEvent?.Invoke(msg);
ArrayEvent?.Invoke(new object[] { DateTime.UtcNow, "Event", msg });
}
[Export]
public double Optional(object a1, int a2, string a3 = "Hello", string a4 = "World")
{
Console.WriteLine($"VoidArgs {a1} {a2} {a3}");
return new Random().NextDouble();
}
[Export]
public AsyncReply<List<Map<int, string?>?>> AsyncHello()
{
var rt = new List<Map<int, string?>?>();
rt.Add(new Map<int, string?>() { [1] = "SSSSS", [2] = null });
return new AsyncReply<List<Map<int, string?>?>>(rt);
}
[Export]
public void Connection(object a1, int a2, EpConnection a3) =>
Console.WriteLine($"VoidArgs {a1} {a2} {a3}");
[Export]
public void ConnectionOptional(object a1, int a2, string a3 = "sss", EpConnection? a4 = null) =>
Console.WriteLine($"VoidArgs {a1} {a2} {a3}");
[Export]
public (int, string) GetTuple2(int a1, string a2) => (a1, a2);
[Export]
public (int, string, double) GetTuple3(int a1, string a2, double a3) => (a1, a2, a3);
[Export]
public (int, string, double, bool) GetTuple4(int a1, string a2, double a3, bool a4) => (a1, a2, a3, a4);
[Export]
public MyRecord SendRecord(MyRecord record)
{
Console.WriteLine(record.ToString());
return record;
}
[Export] public const double PI = Math.PI;
[Export] public MyService Me => this;
[Export] int PrivateInt32 { get; set; } = 99;
}

View File

@@ -0,0 +1,348 @@
/*
Copyright (c) 2017 Ahmed Kh. Zamil
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using Esiur.Data;
using Esiur.Core;
using Esiur.Net.HTTP;
using Esiur.Net.Sockets;
using Esiur.Resource;
using Esiur.Security.Permissions;
using Esiur.Stores;
using System;
using System.Threading;
using System.Threading.Tasks;
using Esiur.Security.Integrity;
using System.Linq;
using Esiur.Data.Types;
using System.Collections;
using System.Runtime.CompilerServices;
using Esiur.Proxy;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using Esiur.Security.Cryptography;
using Esiur.Security.Membership;
using Esiur.Net.Packets;
using System.Numerics;
using Esiur.Protocol;
namespace Esiur.Tests.Distribution;
class Program
{
static void TestSerialization(object x, EpConnection connection = null)
{
var d = Codec.Compose(x, Warehouse.Default, connection);
// var rr = DC.ToHex(y);
var y = Codec.ParseSync(d, 0, Warehouse.Default);
Console.WriteLine($"{x.GetType().Name}: {x} == {y}, {d.ToHex()}");
}
[Export]
public class StudentRecord : IRecord
{
public string Name { get; set; }
public byte Grade { get; set; }
}
public enum LogLevel : int
{
Debug,
Warning,
Error,
}
static async Task Main(string[] args)
{
//TestSerialization("Hello");
//TestSerialization(10);
//TestSerialization(10.1);
//TestSerialization(10.1d);
//TestSerialization((byte)1);
//TestSerialization((byte)2);
TestSerialization(new int[] { 1, 2, 3, 4 });
//var x = LogLevel.Warning;
//TestSerialization(LogLevel.Warning);
//TestSerialization(new Map<string, byte?>
//{
// ["C++"] = 1,
// ["C#"] = 2,
// ["JS"] = null
//});
//TestSerialization(new StudentRecord() { Name = "Ali", Grade = 90 });
//var tn = Encoding.UTF8.GetBytes("Test.StudentRecord");
//var hash = System.Security.Cryptography.SHA256.Create().ComputeHash(tn).Clip(0, 16);
//hash[6] = (byte)((hash[6] & 0xF) | 0x80);
//hash[8] = (byte)((hash[8] & 0xF) | 0x80);
//var g = new UUID(hash);
//Console.WriteLine(g);
var a = new ECDH();
var b = new ECDH();
var apk = a.GetPublicKey();
var bpk = b.GetPublicKey();
var ska = a.ComputeSharedKey(bpk);
var skb = b.ComputeSharedKey(apk);
Console.WriteLine(ska.ToHex());
Console.WriteLine(skb.ToHex());
// Simple membership provider
var membership = new SimpleMembership() { GuestsAllowed = true };
membership.AddUser("user", "123456", new SimpleMembership.QuestionAnswer[0]);
membership.AddUser("admin", "admin", new SimpleMembership.QuestionAnswer[]
{
new SimpleMembership.QuestionAnswer()
{
Question = "What is 5+5",
Answer = 10,
Hashed = true,
}
});
var wh = new Warehouse();
// Create stores to keep objects.
var system = await wh.Put("sys", new MemoryStore());
var server = await wh.Put("sys/server", new EpServer() { Membership = membership });
var web = await wh.Put("sys/web", new HTTPServer() { Port = 8088 });
var service = await wh.Put("sys/service", new MyService());
var res1 = await wh.Put("sys/service/r1", new MyResource() { Description = "Testing 1", CategoryId = 10 });
var res2 = await wh.Put("sys/service/r2", new MyResource() { Description = "Testing 2", CategoryId = 11 });
var res3 = await wh.Put("sys/service/c1", new MyChildResource() { ChildName = "Child 1", Description = "Child Testing 3", CategoryId = 12 });
var res4 = await wh.Put("sys/service/c2", new MyChildResource() { ChildName = "Child 2 Destroy", Description = "Testing Destroy Handler", CategoryId = 12 });
//TestSerialization(res1);
server.MapCall("Hello", (string msg, DateTime time, EpConnection sender) =>
{
Console.WriteLine(msg);
return "Hi " + DateTime.UtcNow;
}).MapCall("temp", () => res4);
service.Resource = res1;
service.ChildResource = res3;
service.Resources = new MyResource[] { res1, res2, res1, res3 };
service.MyResources = new MyResource[] { res1, res2, res3, res4 };
//web.MapGet("/{action}/{age}", (int age, string action, HTTPConnection sender) =>
//{
// Console.WriteLine($"AGE: {age} ACTION: {action}");
// sender.Response.Number = Esiur.Net.Packets.HTTPResponsePacket.ResponseCode.NotFound;
// sender.Send("Not found");
//});
web.MapGet("/", (HTTPConnection sender) =>
{
sender.Send("Hello");
});
await wh.Open();
//var sc = service.GetGenericRecord();
//var d = Codec.Compose(sc, Warehouse.Default, null);
// Start testing
TestClient(service);
}
// AuthorizationRequest, AsyncReply<object>
static AsyncReply<object> Authenticator(AuthorizationRequest x)
{
Console.WriteLine($"Authenticator: {x.Clue}");
var format = x.RequiredFormat;
if (format == EpAuthPacketIAuthFormat.Number)
return new AsyncReply<object>(Convert.ToInt32(10));
else if (format == EpAuthPacketIAuthFormat.Text)
return new AsyncReply<object>(Console.ReadLine().Trim());
throw new NotImplementedException("Not supported format.");
}
private static async void TestClient(IResource local)
{
var con = await new Warehouse().Get<EpConnection>("EP://localhost", new EpConnectionConfig
{
AutoReconnect = true,
Username = "admin",
Password = "admin",
Authenticator = Authenticator
});
dynamic remote = await con.Get("sys/service");
var gr = await remote.GetGenericRecord();
Console.WriteLine(gr);
//return;
Console.WriteLine("OK");
perodicTimer = new Timer(new TimerCallback(perodicTimerElapsed), remote, 0, 1000);
var pcall = await con.Call("Hello", "whats up ?", DateTime.UtcNow);
var temp = await con.Call("temp");
Console.WriteLine("Temp: " + temp.GetHashCode());
//var template = await con.GetTemplateByClassName("Test.MyResource");
TestObjectProps(local, remote);
var opt = await remote.Optional(new { a1 = 22, a2 = 33, a4 = "What?" });
Console.WriteLine(opt);
var hello = await remote.AsyncHello();
await remote.Void();
await remote.Connection("ss", 33);
await remote.ConnectionOptional("Test 2", 88);
var rt = await remote.Optional("Optiona", 311);
Console.WriteLine(rt);
var t2 = await remote.GetTuple2(1, "A");
Console.WriteLine(t2);
var t3 = await remote.GetTuple3(1, "A", 1.3);
Console.WriteLine(t3);
var t4 = await remote.GetTuple4(1, "A", 1.3, true);
Console.WriteLine(t4);
remote.StringEvent += new EpResourceEvent((sender, args) =>
Console.WriteLine($"StringEvent {args}")
);
remote.ArrayEvent += new EpResourceEvent((sender, args) =>
Console.WriteLine($"ArrayEvent {args}")
);
await remote.InvokeEvents("Hello");
//var path = TemplateGenerator.GetTemplate("EP://localhost/sys/service", "Generated");
//Console.WriteLine(path);
}
static async void perodicTimerElapsed(object state)
{
GC.Collect();
try
{
dynamic remote = state;
await remote.InvokeEvents("Hello");
Console.WriteLine("Perodic : " + await remote.AsyncHello());
}
catch (Exception ex)
{
Console.WriteLine("Perodic : " + ex.ToString());
}
}
static Timer perodicTimer;
static void TestObjectProps(IResource local, EpResource remote)
{
foreach (var pt in local.Instance.Definition.Properties)
{
var lv = pt.PropertyInfo.GetValue(local);
object v;
var rv = remote.TryGetPropertyValue(pt.Index, out v);
if (!rv)
Console.WriteLine($" ** {pt.Name} Failed");
else
Console.WriteLine($"{pt.Name} {GetString(lv)} == {GetString(v)}");
}
}
static string GetString(object value)
{
if (value == null)
return "NULL";
var t = value.GetType();
var nt = Nullable.GetUnderlyingType(t);
if (nt != null)
t = nt;
if (t.IsArray)
{
var ar = (Array)value;
if (ar.Length == 0)
return "[]";
var rt = "[";
for (var i = 0; i < ar.Length - 1; i++)
rt += GetString(ar.GetValue(i)) + ",";
rt += GetString(ar.GetValue(ar.Length - 1)) + "]";
return rt;
}
else if (value is Record)
{
return value.ToString();
}
else if (value is IRecord)
{
return "{" + String.Join(", ", t.GetProperties().Select(x => x.Name + ": " + x.GetValue(value))) + "}";
}
else
return value.ToString();
}
}