master
Harald Wolff 2019-04-04 19:34:13 +02:00
parent 0509cc37c0
commit 7c0987e424
4 changed files with 363 additions and 0 deletions

View File

@ -0,0 +1,296 @@
// /**
// * File: JsonCallResource.cs
// * Author: haraldwolff
// *
// * This file and it's content is copyrighted by the Author and / or copyright holder.
// * Any use wihtout proper permission is illegal and may lead to legal actions.
// *
// *
// **/
using System;
using System.Reflection;
using System.Collections.Generic;
using Newtonsoft.Json;
using ln.http.exceptions;
using ln.logging;
using Newtonsoft.Json.Linq;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace ln.http.resources
{
public abstract class ReflectiveResource : Resource
{
public override bool HandlesDispatching => true;
Dictionary<string, MethodInfo[]> callableMethods = new Dictionary<string, MethodInfo[]>();
Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();
Dictionary<string, ReflectiveResource> reflectiveResources = new Dictionary<string, ReflectiveResource>();
public ReflectiveResource(Resource container, string name,object o)
: base(container, name)
{
initialize();
}
private void initialize()
{
Dictionary<string, List<MethodInfo>> callables = new Dictionary<string, List<MethodInfo>>();
foreach (MethodInfo methodInfo in this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
CallableAttribute callableAttribute = methodInfo.GetCustomAttribute<CallableAttribute>();
if (callableAttribute != null)
{
string alias = callableAttribute.Alias == null ? methodInfo.Name : callableAttribute.Alias;
if (!callables.ContainsKey(alias))
{
callables.Add(alias, new List<MethodInfo>());
}
callables[alias].Add(methodInfo);
}
}
foreach (String alias in callables.Keys)
{
callableMethods.Add(alias, callables[alias].ToArray());
new MethodResource(this, alias);
}
foreach (PropertyInfo propertyInfo in this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.GetCustomAttribute<CallableAttribute>() != null)
{
new CallableProperty(this, propertyInfo);
}
}
}
private object InvokeMethodCall(string methodName, object[] arguments)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
MethodInfo methodInfo = FindMethodSignature(methodName, arguments.Length);
object result = methodInfo.Invoke(this, arguments);
stopwatch.Stop();
Logging.Log(LogLevel.DEBUGDETAIL,"InvokeMethodCall({0},...): {1}ms",methodName,stopwatch.ElapsedMilliseconds);
return result;
}
private object InvokeMethodCall(string methodName, KeyValuePair<string,object>[] arguments)
{
MethodInfo methodInfo = FindMethodSignature(methodName, arguments.Select((kvp) => kvp.Key).ToArray());
Dictionary<string, object> args = new Dictionary<string, object>();
foreach (KeyValuePair<string,object> kvp in arguments)
args.Add(kvp.Key, kvp.Value);
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
object[] pl = new object[parameterInfos.Length];
for (int n=0;n<parameterInfos.Length;n++)
pl[n] = args[parameterInfos[n].Name];
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
object result = methodInfo.Invoke(this, pl);
stopwatch.Stop();
Logging.Log(LogLevel.DEBUGDETAIL, "InvokeMethodCall({0},...): {1}ms", methodName, stopwatch.ElapsedMilliseconds);
return result;
}
private MethodInfo FindMethodSignature(String methodName,int nParameters)
{
foreach (MethodInfo methodInfo in callableMethods[methodName])
{
if (nParameters == methodInfo.GetParameters().Length)
{
return methodInfo;
}
}
throw new ArgumentException("No method signature matching the parameters was found");
}
private MethodInfo FindMethodSignature(String methodName, String[] argumentNames)
{
foreach (MethodInfo methodInfo in callableMethods[methodName])
{
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
if (parameterInfos.Length == argumentNames.Length)
{
int n;
for (n = 0; n < parameterInfos.Length; n++)
{
if (!argumentNames.Contains(parameterInfos[n].Name))
break;
}
if (n == argumentNames.Length)
return methodInfo;
}
}
throw new ArgumentException("No method signature matching the parameters was found");
}
public override HttpResponse GetResponse(HttpRequest httpRequest)
{
if (!httpRequest.GetRequestHeader("Content-Type").Equals("application/json"))
{
throw new HttpException("JSON Method call failed, call object not received");
}
MethodCall methodCall = JsonConvert.DeserializeObject<MethodCall>(httpRequest.ContentReader.ReadToEnd());
MethodResult methodResult;
try
{
methodResult = new MethodResult();
methodResult.MethodName = methodCall.MethodName;
methodResult.Result = InvokeMethodCall(methodCall.MethodName, methodCall.Parameters);
} catch (Exception e)
{
methodResult = new MethodResult();
methodResult.MethodName = methodCall.MethodName;
methodResult.Exception = e;
Logging.Log(LogLevel.ERROR, "JsonCallResource: method call caught exception: {0}",e);
Logging.Log(e);
}
String result = JsonConvert.SerializeObject(methodResult);
HttpResponse httpResponse = new HttpResponse(httpRequest);
httpResponse.SetHeader("content-type", "application/json");
httpResponse.ContentWriter.Write(result);
return httpResponse;
}
private string SerializeResult(MethodInfo methodInfo,MethodResult methodResult)
{
if (methodResult.Exception != null)
{
return JsonConvert.SerializeObject(methodResult);
}
else
{
return FlatSerializeResult(methodResult);
}
}
private string FlatSerializeResult(MethodResult methodResult)
{
JObject jMethodResult = new JObject();
jMethodResult.Add("Exception", null);
jMethodResult.Add("MethodName", methodResult.MethodName);
JObject jResult = new JObject();
jMethodResult.Add("Result", jResult);
Type type = methodResult.GetType();
foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
Type fType = fieldInfo.FieldType;
if ((fType.IsValueType) || (typeof(string).Equals(fType)) || (fType.IsArray))
{
jResult.Add(fieldInfo.Name, new JValue(fieldInfo.GetValue(methodResult.Result)));
}
else
{
jResult.Add(fieldInfo.Name, new JValue(fieldInfo.GetValue(methodResult.Result).ToString()));
}
}
return jMethodResult.ToString();
}
class MethodCall
{
public String MethodName;
public object[] Parameters;
}
class MethodResult
{
public String MethodName;
public object Result;
public Exception Exception;
}
class MethodResource : Resource
{
public MethodResource(JsonCallResource container,String methodName)
:base(container,methodName)
{
}
public override HttpResponse GetResponse(HttpRequest httpRequest)
{
throw new NotImplementedException();
}
public override void AddResource(Resource resource) => throw new NotImplementedException();
public override bool Contains(string name) => throw new NotImplementedException();
public override IEnumerable<Resource> GetResources() => throw new NotImplementedException();
public override void RemoveResource(Resource resource) => throw new NotImplementedException();
}
class CallableProperty : Resource
{
public CallableProperty(JsonCallResource container, PropertyInfo propertyInfo)
: base(container, propertyInfo.Name)
{
this.propertyInfo = propertyInfo;
}
PropertyInfo propertyInfo;
public override void AddResource(Resource resource) => throw new NotImplementedException();
public override void RemoveResource(Resource resource) => throw new NotImplementedException();
public override bool Contains(string name) => false;
public override IEnumerable<Resource> GetResources() => new Resource[0];
public override HttpResponse GetResponse(HttpRequest httpRequest)
{
try
{
object v = propertyInfo.GetValue(Container);
String result = JsonConvert.SerializeObject(v);
HttpResponse httpResponse = new HttpResponse(httpRequest);
httpResponse.SetHeader("content-type", "application/json");
httpResponse.ContentWriter.Write(result);
return httpResponse;
} catch (Exception e)
{
Logging.Log(e);
HttpResponse httpResponse = new HttpResponse(httpRequest);
httpResponse.StatusCode = 500;
return httpResponse;
}
}
}
}
}

View File

@ -10,6 +10,8 @@ namespace ln.http.resources
public Resource Container { get; protected set; }
public Resource DefaultResource { get; set; }
public virtual bool HandlesDispatching => false;
public Resource(String name)
{
Name = name;

View File

@ -43,6 +43,8 @@
<Compile Include="BaseResource.cs" />
<Compile Include="TemplateResource.cs" />
<Compile Include="JsonCallResource.cs" />
<Compile Include="ReflectiveResource.cs" />
<Compile Include="reflection\Reflector.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ln.http\ln.http.csproj">
@ -61,5 +63,8 @@
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Folder Include="reflection\" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Reflection;
namespace ln.http.resources.reflection
{
public class Reflector
{
Type TargetType { get; }
Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();
Dictionary<string, MethodInfo> methods = new Dictionary<string, MethodInfo>();
public Reflector(Type targetType)
{
TargetType = targetType;
Initialize();
}
private void Initialize()
{
foreach (PropertyInfo propertyInfo in TargetType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (propertyInfo.GetCustomAttribute<CallableAttribute>() != null)
{
properties.Add(propertyInfo.Name, propertyInfo);
}
}
foreach (MethodInfo methodInfo in TargetType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
if (methodInfo.GetCustomAttribute<CallableAttribute>() != null)
{
methods.Add(methodInfo.Name, methodInfo);
}
}
}
public object InvokeRequest(HttpRequest httpRequest,Queue<string> pathStack,object currentValue)
{
if (pathStack.Count == 0)
return currentValue;
throw new NotImplementedException();
}
static Dictionary<Type, Reflector> reflectorsCache = new Dictionary<Type, Reflector>();
public static Reflector GetReflector(Type targetType)
{
if (!reflectorsCache.ContainsKey(targetType))
{
reflectorsCache[targetType] = new Reflector(targetType);
}
return reflectorsCache[targetType];
}
}
}