2
0
mirror of https://github.com/esiur/esiur-dotnet.git synced 2025-05-06 11:32:59 +00:00
This commit is contained in:
Ahmed Zamil 2020-01-26 14:30:39 +03:00
parent 5f4660fde2
commit 61a1683c26
22 changed files with 409 additions and 346 deletions

View File

@ -11,7 +11,7 @@
<PackageProjectUrl>http://www.esyur.com</PackageProjectUrl> <PackageProjectUrl>http://www.esyur.com</PackageProjectUrl>
<RepositoryUrl>https://github.com/esyur/esyur-dotnet/</RepositoryUrl> <RepositoryUrl>https://github.com/esyur/esyur-dotnet/</RepositoryUrl>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild> <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Version>1.3.0</Version> <Version>1.3.2</Version>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@ -24,7 +24,6 @@ namespace Esyur.Stores.MongoDB
IMongoDatabase database; IMongoDatabase database;
IMongoCollection<BsonDocument> resourcesCollection; IMongoCollection<BsonDocument> resourcesCollection;
Dictionary<string, WeakReference> resources = new Dictionary<string, WeakReference>(); Dictionary<string, WeakReference> resources = new Dictionary<string, WeakReference>();
@ -52,6 +51,13 @@ namespace Esyur.Stores.MongoDB
} }
/*
public IResource[] Query(string json)
{
//var json = "{ SendId: 4, 'Events.Code' : { $all : [2], $nin : [3] } }";
resourcesCollection.Find(new QueryDocument(BsonDocument.Parse(json)));
}*/
public bool Record(IResource resource, string propertyName, object value, ulong age, DateTime date) public bool Record(IResource resource, string propertyName, object value, ulong age, DateTime date)
{ {
@ -98,29 +104,27 @@ namespace Esyur.Stores.MongoDB
return true; return true;
} }
async AsyncReply<T> Fetch<T>(string id) where T : IResource
AsyncReply<T> Fetch<T>(string id) where T : IResource
{ {
if (resources.ContainsKey(id) && resources[id].IsAlive) if (resources.ContainsKey(id) && resources[id].IsAlive)
{ {
if (resources[id].Target is T) if (resources[id].Target is T)
return new AsyncReply<T>((T)resources[id].Target); return (T)resources[id].Target;// new AsyncReply<T>((T)resources[id].Target);
else else
return new AsyncReply<T>(default(T)); ; return default(T);// new AsyncReply<T>(default(T)); ;
} }
var filter = Builders<BsonDocument>.Filter.Eq("_id", new BsonObjectId(new ObjectId(id))); var filter = Builders<BsonDocument>.Filter.Eq("_id", new BsonObjectId(new ObjectId(id)));
var list = resourcesCollection.Find(filter).ToList(); var list = resourcesCollection.Find(filter).ToList();
if (list.Count == 0) if (list.Count == 0)
return new AsyncReply<T>(default(T)); return default(T);// new AsyncReply<T>(default(T));
var document = list[0]; var document = list[0];
var type = Type.GetType(document["classname"].AsString); var type = Type.GetType(document["classname"].AsString);
if (type == null) if (type == null)
return new AsyncReply<T>(default(T)); return default(T);// new AsyncReply<T>(default(T));
IResource resource = (IResource)Activator.CreateInstance(ResourceProxy.GetProxy(type)); IResource resource = (IResource)Activator.CreateInstance(ResourceProxy.GetProxy(type));
@ -142,32 +146,7 @@ namespace Esyur.Stores.MongoDB
resource.Instance.SetAttributes(x as Structure); resource.Instance.SetAttributes(x as Structure);
}); });
var bag = new AsyncBag<object>(); // var bag = new AsyncBag<object>();
/*
foreach (var p in parents)
{
var ap = Warehouse.Get(p.AsString);
bag.Add(ap);
ap.Then((x) =>
{
if (!resource.Instance.Parents.Contains(x))
resource.Instance.Parents.Add(x);
});
}
foreach (var c in children)
{
var ac = Warehouse.Get(c.AsString);
bag.Add(ac);
ac.Then((x) =>
{
if (!resource.Instance.Children.Contains(x))
resource.Instance.Children.Add(x);
});
}
*/
resource.Instance.Attributes.Add("children", children.Select(x => x.AsString).ToArray()); resource.Instance.Attributes.Add("children", children.Select(x => x.AsString).ToArray());
resource.Instance.Attributes.Add("parents", parents.Select(x => x.AsString).ToArray()); resource.Instance.Attributes.Add("parents", parents.Select(x => x.AsString).ToArray());
@ -199,34 +178,19 @@ namespace Esyur.Stores.MongoDB
{ {
var valueInfo = v.Value as BsonDocument; var valueInfo = v.Value as BsonDocument;
var av = Parse(valueInfo["value"]); var x = await Parse(valueInfo["value"]);
av.Then((x) =>
{
resource.Instance.LoadProperty(v.Name, resource.Instance.LoadProperty(v.Name,
(ulong)valueInfo["age"].AsInt64, (ulong)valueInfo["age"].AsInt64,
valueInfo["modification"].ToUniversalTime(), valueInfo["modification"].ToUniversalTime(),
x); x);
});
//bag.Add(av);
bag.Add(av);
} }
var rt = new AsyncReply<T>();
bag.Then((x) =>
{
if (resource is T) if (resource is T)
rt.Trigger(resource); return (T)resource;
else else
rt.Trigger(null); return default(T);
});
bag.Seal();
return rt;
} }
AsyncReply Parse(BsonValue value) AsyncReply Parse(BsonValue value)
@ -314,24 +278,14 @@ namespace Esyur.Stores.MongoDB
return this.Instance.Name + "/id/" + (string)resource.Instance.Attributes["objectId"]; return this.Instance.Name + "/id/" + (string)resource.Instance.Attributes["objectId"];
} }
public bool Put(IResource resource) public async AsyncReply<bool> Put(IResource resource)
{
try
{ {
if (resource == this) if (resource == this)
return true; return true;
PutResource(resource).Wait();
ResourceAdded?.Invoke(resource);
count++;
Instance.Modified("Count");
return true;
}
private async Task<bool> PutResource(IResource resource)
{
var attrs = resource.Instance.GetAttributes(); var attrs = resource.Instance.GetAttributes();
foreach (var kv in resources) foreach (var kv in resources)
@ -341,6 +295,10 @@ namespace Esyur.Stores.MongoDB
return true; return true;
} }
count++;
Instance.Modified("Count");
var type = ResourceProxy.GetBaseType(resource); var type = ResourceProxy.GetBaseType(resource);
// insert the document // insert the document
@ -410,35 +368,29 @@ namespace Esyur.Stores.MongoDB
} }
// var filter = Builders<BsonDocument>.Filter.Eq("_id", document["_id"]);
// var update = Builders<BsonDocument>.Update
// .Set("values", values);
// col.UpdateOne(filter, update);
/*
var document = new BsonDocument
{
{ "parents", parents },
{ "children", children },
{ "attributes", attrsDoc },
{ "classname", resource.GetType().FullName + "," + resource.GetType().GetTypeInfo().Assembly.GetName().Name },
{ "name", resource.Instance.Name },
{ "values", values }
};
*/
var filter = Builders<BsonDocument>.Filter.Eq("_id", document["_id"]); var filter = Builders<BsonDocument>.Filter.Eq("_id", document["_id"]);
var update = Builders<BsonDocument>.Update var update = Builders<BsonDocument>.Update
.Set("values", values).Set("parents", parents).Set("children", children).Set("attributes", attrsDoc); .Set("values", values).Set("parents", parents).Set("children", children).Set("attributes", attrsDoc);
resourcesCollection.UpdateOne(filter, update); resourcesCollection.UpdateOne(filter, update);
resources.Add(document["_id"].AsObjectId.ToString(), new WeakReference(resource));
//resource.Instance.Attributes["objectId"] = document["_id"].ToString(); //resource.Instance.Attributes["objectId"] = document["_id"].ToString();
ResourceAdded?.Invoke(resource);
return true; return true;
} }
catch(Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public BsonDocument ComposeStructure(Structure value) public BsonDocument ComposeStructure(Structure value)
@ -453,12 +405,12 @@ namespace Esyur.Stores.MongoDB
return rt; return rt;
} }
public BsonArray ComposeVarArray(object[] array) public BsonArray ComposeVarArray(Array array)
{ {
var rt = new BsonArray(); var rt = new BsonArray();
for (var i = 0; i < array.Length; i++) for (var i = 0; i < array.Length; i++)
rt.Add(Compose(array[i])); rt.Add(Compose(array.GetValue(i)));// [i]));
return rt; return rt;
} }
@ -491,9 +443,9 @@ namespace Esyur.Stores.MongoDB
return rt; return rt;
} }
private BsonValue Compose(object value) private BsonValue Compose(object valueObj)
{ {
var type = Codec.GetDataType(value, null); var (type, value) = Codec.GetDataType(valueObj, null);
switch (type) switch (type)
{ {
@ -515,7 +467,7 @@ namespace Esyur.Stores.MongoDB
return ComposeStructure((Structure)value); return ComposeStructure((Structure)value);
case DataType.VarArray: case DataType.VarArray:
return ComposeVarArray((object[])value); return ComposeVarArray((Array)value);
case DataType.ResourceArray: case DataType.ResourceArray:
if (value is IResource[]) if (value is IResource[])

View File

@ -227,9 +227,6 @@ namespace Esyur.Core
{ {
//timeout?.Dispose(); //timeout?.Dispose();
if (resultReady)
return;
//lock (callbacksLock) //lock (callbacksLock)
//{ //{
foreach (var cb in progressCallbacks) foreach (var cb in progressCallbacks)
@ -244,8 +241,6 @@ namespace Esyur.Core
//timeout?.Dispose(); //timeout?.Dispose();
if (resultReady)
return;
//lock (callbacksLock) //lock (callbacksLock)
//{ //{

View File

@ -8,6 +8,8 @@ namespace Esyur.Core
{ {
HostNotReachable, HostNotReachable,
AccessDenied, AccessDenied,
UserNotFound,
ChallengeFailed,
ResourceNotFound, ResourceNotFound,
AttachDenied, AttachDenied,
InvalidMethod, InvalidMethod,

View File

@ -73,7 +73,9 @@ namespace Esyur.Data
var types = new DataType[keys.Length]; var types = new DataType[keys.Length];
for (var i = 0; i < keys.Length; i++) for (var i = 0; i < keys.Length; i++)
types[i] = Codec.GetDataType(structure[keys[i]], connection); {
types[i] = Codec.GetDataType(structure[keys[i]], connection).type;
}
return types; return types;
} }
@ -434,7 +436,7 @@ namespace Esyur.Data
return new AsyncReply<char[]>(data.GetCharArray(offset, contentLength)); return new AsyncReply<char[]>(data.GetCharArray(offset, contentLength));
case DataType.Int16: case DataType.Int16:
return new AsyncReply<short[]>(data.GetInt16Array( offset, contentLength)); return new AsyncReply<short[]>(data.GetInt16Array(offset, contentLength));
case DataType.UInt16: case DataType.UInt16:
return new AsyncReply<ushort[]>(data.GetUInt16Array(offset, contentLength)); return new AsyncReply<ushort[]>(data.GetUInt16Array(offset, contentLength));
@ -756,12 +758,12 @@ namespace Esyur.Data
/// <param name="connection">DistributedConnection is required to check locality.</param> /// <param name="connection">DistributedConnection is required to check locality.</param>
/// <param name="prependLength">If True, prepend the length as UInt32 at the beginning of the output.</param> /// <param name="prependLength">If True, prepend the length as UInt32 at the beginning of the output.</param>
/// <returns>Array of bytes in the network byte order.</returns> /// <returns>Array of bytes in the network byte order.</returns>
public static byte[] ComposeVarArray(object[] array, DistributedConnection connection, bool prependLength = false) public static byte[] ComposeVarArray(Array array, DistributedConnection connection, bool prependLength = false)
{ {
var rt = new List<byte>(); var rt = new List<byte>();
for (var i = 0; i < array.Length; i++) for (var i = 0; i < array.Length; i++)
rt.AddRange(Compose(array[i], connection)); rt.AddRange(Compose(array.GetValue(i), connection));
if (prependLength) if (prependLength)
rt.InsertRange(0, DC.ToBytes(rt.Count)); rt.InsertRange(0, DC.ToBytes(rt.Count));
return rt.ToArray(); return rt.ToArray();
@ -928,7 +930,7 @@ namespace Esyur.Data
bagOfBags.Then(x => bagOfBags.Then(x =>
{ {
for(var i = 0; i < list.Count; i++) for (var i = 0; i < list.Count; i++)
list[list.Keys.ElementAt(i)] = x[i]; list[list.Keys.ElementAt(i)] = x[i];
reply.Trigger(list); reply.Trigger(list);
@ -1001,15 +1003,10 @@ namespace Esyur.Data
/// <param name="connection">DistributedConnection is required to check locality.</param> /// <param name="connection">DistributedConnection is required to check locality.</param>
/// <param name="prependType">If True, prepend the DataType at the beginning of the output.</param> /// <param name="prependType">If True, prepend the DataType at the beginning of the output.</param>
/// <returns>Array of bytes in the network byte order.</returns> /// <returns>Array of bytes in the network byte order.</returns>
public static byte[] Compose(object value, DistributedConnection connection, bool prependType = true) public static byte[] Compose(object valueOrSource, DistributedConnection connection, bool prependType = true)
{ {
if (value is Func<DistributedConnection, object>) var (type, value) = GetDataType(valueOrSource, connection);
value = (value as Func<DistributedConnection, object>)(connection);
else if (value is DistributedPropertyContext)
value = (value as DistributedPropertyContext).Method(connection);
var type = GetDataType(value, connection);
var rt = new BinaryList(); var rt = new BinaryList();
switch (type) switch (type)
@ -1038,7 +1035,7 @@ namespace Esyur.Data
break; break;
case DataType.VarArray: case DataType.VarArray:
rt.AddUInt8Array(ComposeVarArray((object[])value, connection, true)); rt.AddUInt8Array(ComposeVarArray((Array)value, connection, true));
break; break;
case DataType.ResourceArray: case DataType.ResourceArray:
@ -1165,10 +1162,30 @@ namespace Esyur.Data
/// <param name="value">Value to find its DataType.</param> /// <param name="value">Value to find its DataType.</param>
/// <param name="connection">DistributedConnection is required to check locality of resources.</param> /// <param name="connection">DistributedConnection is required to check locality of resources.</param>
/// <returns>DataType.</returns> /// <returns>DataType.</returns>
public static DataType GetDataType(object value, DistributedConnection connection) public static (DataType type, object value) GetDataType(object value, DistributedConnection connection)
{ {
if (value == null) if (value == null)
return DataType.Void; return (DataType.Void, null);
if (value is IUserType)
value = (value as IUserType).Get();
if (value is Func<DistributedConnection, object>)
//if (connection != null)
value = (value as Func<DistributedConnection, object>)(connection);
//else
// return (DataType.Void, null);
else if (value is DistributedPropertyContext)
//if (connection != null)
value = (value as DistributedPropertyContext).Method(connection);
//else
// return (DataType.Void, null);
if (value == null)
return (DataType.Void, null);
var t = value.GetType(); var t = value.GetType();
@ -1208,17 +1225,17 @@ namespace Esyur.Data
type = DataType.String; type = DataType.String;
else if (t == typeof(DateTime)) else if (t == typeof(DateTime))
type = DataType.DateTime; type = DataType.DateTime;
else if (t == typeof(Structure)) else if (typeof(Structure).IsAssignableFrom(t))
type = DataType.Structure; type = DataType.Structure;
//else if (t == typeof(DistributedResource)) //else if (t == typeof(DistributedResource))
// type = DataType.DistributedResource; // type = DataType.DistributedResource;
else if (ImplementsInterface(t, typeof(IResource))) else if (ImplementsInterface(t, typeof(IResource)))
{ {
if (isArray) if (isArray)
return DataType.ResourceArray; return (DataType.ResourceArray, value);
else else
{ {
return IsLocalResource((IResource)value, connection) ? DataType.Resource : DataType.DistributedResource; return (IsLocalResource((IResource)value, connection) ? DataType.Resource : DataType.DistributedResource, value);
} }
} }
else else
@ -1226,9 +1243,9 @@ namespace Esyur.Data
if (isArray) if (isArray)
return (DataType)((byte)type | 0x80); return ((DataType)((byte)type | 0x80), value);
else else
return type; return (type, value);
} }

View File

@ -43,9 +43,13 @@ namespace Esyur.Data
{ {
public static object CastConvert(object value, Type destinationType) public static object CastConvert(object value, Type destinationType)
{ {
if (value == null) if (value == null)
return null; return null;
//if (destinationType.IsArray && destinationType.GetElementType().IsArray)
// Console.Beep();
var sourceType = value.GetType(); var sourceType = value.GetType();
if (destinationType == sourceType) if (destinationType == sourceType)
@ -54,9 +58,8 @@ namespace Esyur.Data
} }
else else
{ {
if (sourceType.IsArray) if (sourceType.IsArray && (destinationType.IsArray || destinationType == typeof(object)))
{ {
if (destinationType.IsArray)
destinationType = destinationType.GetElementType(); destinationType = destinationType.GetElementType();
var v = value as Array; var v = value as Array;
@ -65,29 +68,34 @@ namespace Esyur.Data
for (var i = 0; i < rt.Length; i++) for (var i = 0; i < rt.Length; i++)
{ {
try rt.SetValue(CastConvert(v.GetValue(i), destinationType), i);
{
#if NETSTANDARD // try
if (destinationType.GetTypeInfo().IsInstanceOfType(v.GetValue(i))) // {
#else //#if NETSTANDARD
if (destinationType.IsInstanceOfType(v.GetValue(i))) // if (destinationType.GetTypeInfo().IsInstanceOfType(v.GetValue(i)))
#endif //#else
rt.SetValue(v.GetValue(i), i); // if (destinationType.IsInstanceOfType(v.GetValue(i)))
else //#endif
rt.SetValue(Convert.ChangeType(v.GetValue(i), destinationType), i); // rt.SetValue(v.GetValue(i), i);
} // else
catch // rt.SetValue(Convert.ChangeType(v.GetValue(i), destinationType), i);
{ // }
rt.SetValue(null, i); // catch
} // {
// rt.SetValue(null, i);
// }
} }
return rt; return rt;
} }
else else
{ {
try try
{ {
var underType = Nullable.GetUnderlyingType(destinationType); var underType = Nullable.GetUnderlyingType(destinationType);
if (underType != null) if (underType != null)
{ {
@ -97,15 +105,26 @@ namespace Esyur.Data
destinationType = underType; destinationType = underType;
} }
#if NETSTANDARD
if (destinationType.GetTypeInfo().IsInstanceOfType(value))
#else
if (destinationType.IsInstanceOfType(value)) if (destinationType.IsInstanceOfType(value))
#endif {
return value; return value;
}
else if (typeof(IUserType).IsAssignableFrom(destinationType))
{
var rt = Activator.CreateInstance(destinationType) as IUserType;
rt.Set(value);
return rt;
}
else if (sourceType == typeof(Structure) && sourceType.IsAssignableFrom(destinationType))
{
return Structure.FromStructure((Structure)value, destinationType);
}
else else
{
return Convert.ChangeType(value, destinationType); return Convert.ChangeType(value, destinationType);
} }
}
catch catch
{ {
return null; return null;

12
Esyur/Data/IUserType.cs Normal file
View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Esyur.Data
{
public interface IUserType
{
object Get();
void Set(object value);
}
}

View File

@ -57,11 +57,33 @@ namespace Esyur.Data
{ {
var rt = ""; var rt = "";
foreach (var kv in dic) foreach (var kv in dic)
rt += kv.Key + ": " + kv.Value.ToString() + "\r\n"; rt += kv.Key + ": " + kv.Value.ToString() + " \r\n";
return rt.TrimEnd('\r', '\n'); return rt.TrimEnd('\r', '\n');
} }
public Structure(Structure source)
{
dic = source.dic;
}
public Structure()
{
}
public static Structure FromStructure(Structure source, Type destinationType)
{
var rt = Activator.CreateInstance(destinationType) as Structure;
rt.dic = source.dic;
return rt;
}
public static T FromStructure<T>(Structure source) where T : Structure
{
var rt = Activator.CreateInstance<T>();
rt.dic = source.dic;
return rt;
}
public static Structure FromObject(object obj) public static Structure FromObject(object obj)
{ {

View File

@ -7,7 +7,7 @@
<PackageLicenseUrl>https://github.com/Esyur/Esyur-dotnet/blob/master/LICENSE</PackageLicenseUrl> <PackageLicenseUrl>https://github.com/Esyur/Esyur-dotnet/blob/master/LICENSE</PackageLicenseUrl>
<PackageProjectUrl>http://www.esyur.com</PackageProjectUrl> <PackageProjectUrl>http://www.esyur.com</PackageProjectUrl>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.4.5</Version> <Version>1.4.7</Version>
<RepositoryUrl>https://github.com/esyur/esyur-dotnet</RepositoryUrl> <RepositoryUrl>https://github.com/esyur/esyur-dotnet</RepositoryUrl>
<Authors>Ahmed Kh. Zamil</Authors> <Authors>Ahmed Kh. Zamil</Authors>
<AssemblyVersion>1.3.1.0</AssemblyVersion> <AssemblyVersion>1.3.1.0</AssemblyVersion>

View File

@ -410,7 +410,7 @@ namespace Esyur.Misc
public static string GenerateCode(int length) public static string GenerateCode(int length)
{ {
return GenerateCode(length, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_-+=\\?/"); return GenerateCode(length, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");// ~!@#$%^&*()_-+=\\?/");
} }
public static string GenerateCode(int length, string chars) public static string GenerateCode(int length, string chars)

View File

@ -225,7 +225,6 @@ namespace Esyur.Net.HTTP
} }
} }
bool bb;
public void SendFile(string filename) public void SendFile(string filename)
{ {
@ -299,7 +298,7 @@ namespace Esyur.Net.HTTP
if (n <= 0) if (n <= 0)
break; break;
Thread.Sleep(50);
base.Send(buffer, 0, n); base.Send(buffer, 0, n);
} }

View File

@ -53,48 +53,48 @@ namespace Esyur.Net.HTTP
} }
[Storable] [Storable]
string ip public virtual string ip
{ {
get; get;
set; set;
} }
[Storable] [Storable]
ushort port public virtual ushort port
{ {
get; get;
set; set;
} }
[Storable] [Storable]
uint timeout public virtual uint timeout
{ {
get; get;
set; set;
} }
[Storable] [Storable]
uint clock public virtual uint clock
{ {
get; get;
set; set;
} }
[Storable] [Storable]
uint maxPost public virtual uint maxPost
{ {
get; get;
set; set;
} }
[Storable] [Storable]
bool ssl public virtual bool ssl
{ {
get; get;
set; set;
} }
[Storable] [Storable]
string certificate public virtual string certificate
{ {
get; get;
set; set;
@ -380,6 +380,11 @@ namespace Esyur.Net.HTTP
sender.SetParent(this); sender.SetParent(this);
//Console.WriteLine("IN: " + this.Connections.Count); //Console.WriteLine("IN: " + this.Connections.Count);
if (filters == null)
{
sender.Close();
return;
}
foreach (var resource in filters) foreach (var resource in filters)
{ {

View File

@ -610,8 +610,10 @@ namespace Esyur.Net.IIP
else else
{ {
//Console.WriteLine("User not found"); //Console.WriteLine("User not found");
//SendParams((byte)0xc0, (byte)1, (ushort)14, DC.ToBytes("User not found")); SendParams().AddUInt8(0xc0)
SendParams().AddUInt8(0xc0).AddUInt8(1).AddUInt16(14).AddString("User not found").Done(); .AddUInt8((byte)ExceptionCode.UserNotFound)
.AddUInt16(14)
.AddString("User not found").Done();
} }
}); });
@ -649,9 +651,11 @@ namespace Esyur.Net.IIP
else else
{ {
//Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:DENIED"); //Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:DENIED");
//Console.WriteLine("Incorrect password"); SendParams().AddUInt8(0xc0)
//SendParams((byte)0xc0, (byte)1, (ushort)5, DC.ToBytes("Error")); .AddUInt8((byte)ExceptionCode.AccessDenied)
SendParams().AddUInt8(0xc0).AddUInt8(1).AddUInt16(5).AddString("Error").Done(); .AddUInt16(13)
.AddString("Access Denied")
.Done();
} }
} }
}); });
@ -729,9 +733,9 @@ namespace Esyur.Net.IIP
{ {
SendParams() SendParams()
.AddUInt8(0xc0) .AddUInt8(0xc0)
.AddUInt8(1) .AddUInt8((byte)ExceptionCode.ChallengeFailed)
.AddUInt16(5) .AddUInt16(16)
.AddString("Error") .AddString("Challenge Failed")
.Done(); .Done();
//SendParams((byte)0xc0, 1, (ushort)5, DC.ToBytes("Error")); //SendParams((byte)0xc0, 1, (ushort)5, DC.ToBytes("Error"));
@ -789,7 +793,6 @@ namespace Esyur.Net.IIP
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex); Console.WriteLine(ex);
Console.Beep();
} }
finally finally
{ {
@ -830,7 +833,7 @@ namespace Esyur.Net.IIP
var sock = new TCPSocket(); var sock = new TCPSocket();
sock.Connect(domain, port).Then((x)=> { sock.Connect(address, port).Then((x)=> {
Assign(sock); Assign(sock);
//rt.trigger(true); //rt.trigger(true);
}).Error((x) => }).Error((x) =>
@ -849,7 +852,7 @@ namespace Esyur.Net.IIP
/// </summary> /// </summary>
/// <param name="resource">Resource.</param> /// <param name="resource">Resource.</param>
/// <returns></returns> /// <returns></returns>
public bool Put(IResource resource) public async AsyncReply<bool> Put(IResource resource)
{ {
if (Codec.IsLocalResource(resource, this)) if (Codec.IsLocalResource(resource, this))
resources.Add((resource as DistributedResource).Id, (DistributedResource)resource); resources.Add((resource as DistributedResource).Id, (DistributedResource)resource);

View File

@ -1097,6 +1097,10 @@ namespace Esyur.Net.IIP
var ft = r.Instance.Template.GetFunctionTemplateByIndex(index); var ft = r.Instance.Template.GetFunctionTemplateByIndex(index);
if (ft != null) if (ft != null)
{ {
// un hold the socket to send data immediately
this.Socket.Unhold();
if (r is DistributedResource) if (r is DistributedResource)
{ {
var rt = (r as DistributedResource)._InvokeByArrayArguments(index, arguments); var rt = (r as DistributedResource)._InvokeByArrayArguments(index, arguments);
@ -1163,7 +1167,8 @@ namespace Esyur.Net.IIP
} }
catch (Exception ex) catch (Exception ex)
{ {
SendError(ErrorType.Exception, callback, 0, ex.InnerException.ToString()); SendError(ErrorType.Exception, callback, 0,
ex.InnerException != null ? ex.InnerException.ToString() : ex.ToString());
return; return;
} }
@ -1171,12 +1176,18 @@ namespace Esyur.Net.IIP
{ {
var enu = rt as System.Collections.IEnumerable; var enu = rt as System.Collections.IEnumerable;
try
{
foreach (var v in enu) foreach (var v in enu)
SendChunk(callback, v); SendChunk(callback, v);
SendReply(IIPPacket.IIPPacketAction.InvokeFunctionArrayArguments, callback) SendReply(IIPPacket.IIPPacketAction.InvokeFunctionArrayArguments, callback)
.AddUInt8((byte)DataType.Void) .AddUInt8((byte)DataType.Void)
.Done(); .Done();
}
catch(Exception ex)
{
SendError(ErrorType.Exception, callback, 0, ex.ToString());
}
} }
else if (rt is Task) else if (rt is Task)
@ -1254,6 +1265,9 @@ namespace Esyur.Net.IIP
var ft = r.Instance.Template.GetFunctionTemplateByIndex(index); var ft = r.Instance.Template.GetFunctionTemplateByIndex(index);
if (ft != null) if (ft != null)
{ {
// un hold the socket to send data immediately
this.Socket.Unhold();
if (r is DistributedResource) if (r is DistributedResource)
{ {
var rt = (r as DistributedResource)._InvokeByNamedArguments(index, namedArgs); var rt = (r as DistributedResource)._InvokeByNamedArguments(index, namedArgs);
@ -1323,6 +1337,8 @@ namespace Esyur.Net.IIP
{ {
var enu = rt as System.Collections.IEnumerable; var enu = rt as System.Collections.IEnumerable;
try
{
foreach (var v in enu) foreach (var v in enu)
SendChunk(callback, v); SendChunk(callback, v);
@ -1330,6 +1346,11 @@ namespace Esyur.Net.IIP
.AddUInt8((byte)DataType.Void) .AddUInt8((byte)DataType.Void)
.Done(); .Done();
} }
catch (Exception ex)
{
SendError(ErrorType.Exception, callback, 0, ex.ToString());
}
}
else if (rt is Task) else if (rt is Task)
{ {
(rt as Task).ContinueWith(t => (rt as Task).ContinueWith(t =>

View File

@ -284,9 +284,9 @@ namespace Esyur.Net
sock.Send(msg, offset, length); sock.Send(msg, offset, length);
} }
} }
catch catch (Exception ex)
{ {
Console.WriteLine(ex);
} }
} }

View File

@ -50,6 +50,7 @@ namespace Esyur.Net.Sockets
event ISocketConnectEvent OnConnect; event ISocketConnectEvent OnConnect;
event ISocketCloseEvent OnClose; event ISocketCloseEvent OnClose;
void Send(byte[] message); void Send(byte[] message);
void Send(byte[] message, int offset, int size); void Send(byte[] message, int offset, int size);
void Close(); void Close();

View File

@ -48,7 +48,7 @@ namespace Esyur.Net.Sockets
NetworkBuffer receiveNetworkBuffer = new NetworkBuffer(); NetworkBuffer receiveNetworkBuffer = new NetworkBuffer();
object sendLock = new object(); readonly object sendLock = new object();
Queue<byte[]> sendBufferQueue = new Queue<byte[]>(); Queue<byte[]> sendBufferQueue = new Queue<byte[]>();
@ -238,39 +238,39 @@ namespace Esyur.Net.Sockets
} }
private void DataSent(Task<int> task) //private void DataSent(Task<int> task)
{ //{
try // try
{ // {
lock (sendLock) // lock (sendLock)
{ // {
if (sendBufferQueue.Count > 0) // if (sendBufferQueue.Count > 0)
{ // {
byte[] data = sendBufferQueue.Dequeue(); // byte[] data = sendBufferQueue.Dequeue();
//Console.WriteLine(Encoding.UTF8.GetString(data)); // //Console.WriteLine(Encoding.UTF8.GetString(data));
sock.SendAsync(new ArraySegment<byte>(data), SocketFlags.None).ContinueWith(DataSent); // sock.SendAsync(new ArraySegment<byte>(data), SocketFlags.None).ContinueWith(DataSent);
} // }
else // else
{ // {
asyncSending = false; // asyncSending = false;
} // }
} // }
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
if (state != SocketState.Closed && !sock.Connected) // if (state != SocketState.Closed && !sock.Connected)
{ // {
state = SocketState.Terminated; // state = SocketState.Terminated;
Close(); // Close();
} // }
asyncSending = false; // asyncSending = false;
Global.Log("TCPSocket", LogType.Error, ex.ToString()); // Global.Log("TCPSocket", LogType.Error, ex.ToString());
} // }
} //}
public TCPSocket(IPEndPoint localEndPoint) public TCPSocket(IPEndPoint localEndPoint)
{ {
@ -348,44 +348,46 @@ namespace Esyur.Net.Sockets
public void Send(byte[] message, int offset, int size) public void Send(byte[] message, int offset, int size)
{ {
//sock.Blocking =
//sock.Send(message, offset, size, SocketFlags.None); var msg = message.Clip((uint)offset, (uint)size);
//return;
if (sock.Connected)
lock (sendLock) lock (sendLock)
{ {
if (!sock.Connected)
return;
if (asyncSending || held) if (asyncSending || held)
{ {
sendBufferQueue.Enqueue(message.Clip((uint)offset, (uint)size)); sendBufferQueue.Enqueue(msg);
} }
else else
{ {
asyncSending = true; asyncSending = true;
sock.BeginSend(message, offset, size, SocketFlags.None, PacketSent, null); sock.BeginSend(msg, 0, size, SocketFlags.None, PacketSent, null);
//sock.SendAsync(new ArraySegment<byte>(msg), SocketFlags.None).ContinueWith(DataSent); //sock.SendAsync(new ArraySegment<byte>(msg), SocketFlags.None).ContinueWith(DataSent);
} }
} }
} }
private void PacketSent(IAsyncResult ar) private void PacketSent(IAsyncResult ar)
{ {
try try
{
if (sendBufferQueue.Count > 0)
{ {
lock (sendLock) lock (sendLock)
{
if (sendBufferQueue.Count > 0)
{ {
byte[] data = sendBufferQueue.Dequeue(); byte[] data = sendBufferQueue.Dequeue();
sock.BeginSend(data, 0, data.Length, SocketFlags.None, PacketSent, null); sock.BeginSend(data, 0, data.Length, SocketFlags.None, PacketSent, null);
} }
}
else else
{ {
asyncSending = false; asyncSending = false;
} }
} }
}
catch (Exception ex) catch (Exception ex)
{ {
if (state != SocketState.Closed && !sock.Connected) if (state != SocketState.Closed && !sock.Connected)
@ -447,12 +449,11 @@ namespace Esyur.Net.Sockets
{ {
try try
{ {
DataSent(null); PacketSent(null);
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex); Console.WriteLine(ex);
Console.Beep();
} }
finally finally
{ {

View File

@ -37,7 +37,7 @@ namespace Esyur.Resource
{ {
AsyncReply<IResource> Get(string path);//, Func<IResource, bool> filter = null); AsyncReply<IResource> Get(string path);//, Func<IResource, bool> filter = null);
//AsyncReply<IResource> Retrieve(uint iid); //AsyncReply<IResource> Retrieve(uint iid);
bool Put(IResource resource); AsyncReply<bool> Put(IResource resource);
string Link(IResource resource); string Link(IResource resource);
bool Record(IResource resource, string propertyName, object value, ulong age, DateTime dateTime); bool Record(IResource resource, string propertyName, object value, ulong age, DateTime dateTime);
bool Modify(IResource resource, string propertyName, object value, ulong age, DateTime dateTime); bool Modify(IResource resource, string propertyName, object value, ulong age, DateTime dateTime);

View File

@ -394,6 +394,7 @@ namespace Esyur.Resource
if (resource.TryGetTarget(out res)) if (resource.TryGetTarget(out res))
{ {
var rt = pt.Serilize ? pt.Info.GetValue(res, null) : null; var rt = pt.Serilize ? pt.Info.GetValue(res, null) : null;
props.Add(new PropertyValue(rt, ages[pt.Index], modificationDates[pt.Index])); props.Add(new PropertyValue(rt, ages[pt.Index], modificationDates[pt.Index]));
} }
//} //}

View File

@ -111,30 +111,38 @@ namespace Esyur.Resource
/// <returns>True, if no problem occurred.</returns> /// <returns>True, if no problem occurred.</returns>
public static async AsyncReply<bool> Open() public static async AsyncReply<bool> Open()
{ {
warehouseIsOpen = true;
foreach (var rk in resources) var resSnap = resources.Select(x => {
{
IResource r; IResource r;
if (rk.Value.TryGetTarget(out r)) if (x.Value.TryGetTarget(out r))
return r;
else
return null;
}).Where(r=>r!=null).ToArray();
foreach (var r in resSnap)
{ {
//IResource r;
//if (rk.Value.TryGetTarget(out r))
//{
var rt = await r.Trigger(ResourceTrigger.Initialize); var rt = await r.Trigger(ResourceTrigger.Initialize);
if (!rt) if (!rt)
return false; return false;
} //}
} }
foreach (var rk in resources) foreach (var r in resSnap)
{
IResource r;
if (rk.Value.TryGetTarget(out r))
{ {
//IResource r;
//if (rk.Value.TryGetTarget(out r))
//{
var rt = await r.Trigger(ResourceTrigger.SystemInitialized); var rt = await r.Trigger(ResourceTrigger.SystemInitialized);
if (!rt) if (!rt)
return false; return false;
} //}
} }
warehouseIsOpen = true;
return true; return true;
@ -422,6 +430,8 @@ namespace Esyur.Resource
/// <param name="parent">Parent resource. if not presented the store becomes the parent for the resource.</param> /// <param name="parent">Parent resource. if not presented the store becomes the parent for the resource.</param>
public static void Put(IResource resource, string name, IStore store = null, IResource parent = null, ResourceTemplate customTemplate = null, ulong age = 0, IPermissionsManager manager = null, object attributes = null) public static void Put(IResource resource, string name, IStore store = null, IResource parent = null, ResourceTemplate customTemplate = null, ulong age = 0, IPermissionsManager manager = null, object attributes = null)
{ {
if (resource.Instance != null)
throw new Exception("Resource has a store.");
if (store == null) if (store == null)
{ {
@ -467,6 +477,8 @@ namespace Esyur.Resource
if (resource is IStore) if (resource is IStore)
StoreConnected?.Invoke(resource as IStore, name); StoreConnected?.Invoke(resource as IStore, name);
//else //else
store.Put(resource); store.Put(resource);
@ -481,6 +493,7 @@ namespace Esyur.Resource
var t = resource.GetType(); var t = resource.GetType();
Global.Counters["T-" + t.Namespace + "." + t.Name]++; Global.Counters["T-" + t.Namespace + "." + t.Name]++;
lock (resourcesLock)
resources.Add(resource.Instance.Id, new WeakReference<IResource>(resource)); resources.Add(resource.Instance.Id, new WeakReference<IResource>(resource));
if (warehouseIsOpen) if (warehouseIsOpen)

View File

@ -41,7 +41,7 @@ namespace Esyur.Stores
return new AsyncReply<IResource>(null); return new AsyncReply<IResource>(null);
} }
public bool Put(IResource resource) public async AsyncReply<bool> Put(IResource resource)
{ {
resources.Add(resource.Instance.Id, resource);// new WeakReference<IResource>(resource)); resources.Add(resource.Instance.Id, resource);// new WeakReference<IResource>(resource));

View File

@ -31,16 +31,16 @@ namespace Esyur.Stores
return null; return null;
} }
public AsyncReply<IResource> Get(string path) public async AsyncReply<IResource> Get(string path)
{ {
foreach (var r in resources) foreach (var r in resources)
if (r.Value.IsAlive && (r.Value.Target as IResource).Instance.Name == path) if (r.Value.IsAlive && (r.Value.Target as IResource).Instance.Name == path)
return new AsyncReply<IResource>(r.Value.Target as IResource); return r.Value.Target as IResource;
return new AsyncReply<IResource>(null); return null;
} }
public bool Put(IResource resource) public async AsyncReply<bool> Put(IResource resource)
{ {
resources.Add(resource.Instance.Id, new WeakReference( resource));// new WeakReference<IResource>(resource)); resources.Add(resource.Instance.Id, new WeakReference( resource));// new WeakReference<IResource>(resource));
return true; return true;