public void TestConstructorResolutionWith2IntParamWhenOneIsNull()
        {
            MethodCache cache = new MethodCache();
            var         obj   = cache.CreateInstance <Sample1>(BindingFlags.NonPublic | BindingFlags.Instance, 1, null);

            obj.Prop.Should().Be(1);
        }
        public void TestConstructorResolutionWith2IntParam()
        {
            MethodCache cache = new MethodCache();
            var         obj1  = cache.CreateInstance <Sample1>(BindingFlags.NonPublic | BindingFlags.Instance, 1, 2);

            obj1.Prop.Should().Be(3);
        }
        public void TestConstructorResolutionWith1StringWrongParam()
        {
            MethodCache cache = new MethodCache();

            Assert.Throws <FormatException>(() =>
                                            cache.CreateInstance <Sample1>("a"));
        }
        public void TestConstructorResolutionWith1StringParam()
        {
            MethodCache cache = new MethodCache();
            var         obj1  = cache.CreateInstance <Sample1>("1");

            obj1.Prop.Should().Be(1);
        }
        public void TestConstructorThatDoesntExist()
        {
            MethodCache cache = new MethodCache();

            Assert.Throws <MissingMethodException>(() =>
                                                   cache.CreateInstance <Sample1>("asd", null, 1));
        }
Exemplo n.º 6
0
        public void TestConstructorResolutionWith2IntParam()
        {
            MethodCache cache = new MethodCache();
            var obj1 = cache.CreateInstance<Sample1>(BindingFlags.NonPublic | BindingFlags.Instance, 1, 2);

            obj1.Prop.Should().Be(3);
        }
Exemplo n.º 7
0
 public CompilationCache(string pNamespace)
 {
     Namespace   = pNamespace;
     _types      = new SmallTypeCache();
     _methods    = new MethodCache();
     _references = new Dictionary <string, CompilationModule>();
 }
        public void TestConstructorResolutionWithNoParams()
        {
            MethodCache cache = new MethodCache();
            var         obj1  = cache.CreateInstance <Sample1>();

            obj1.Prop.Should().Be(0);
        }
Exemplo n.º 9
0
 public void ConvertNewToOverrides(ModuleDefinition module)
 {
     foreach (var type in module.GetTypes())
     {
         if (type.IsInterface)
         {
             continue;
         }
         if (type.IsEnum)
         {
             continue;
         }
         var baseTypes   = GetBaseTypes(type).ToList();
         var baseMethods = MethodCache.Where(x => baseTypes.Contains(x.DeclaringType)).ToList();
         if (baseMethods.Count == 0)
         {
             continue;
         }
         foreach (var methodDefinition in type.Methods)
         {
             Replace(methodDefinition, baseMethods);
         }
         foreach (var propertyDefinition in type.Properties)
         {
             Replace(propertyDefinition.GetMethod, baseMethods);
             Replace(propertyDefinition.SetMethod, baseMethods);
         }
     }
 }
Exemplo n.º 10
0
        public void TestConstructorResolutionWithNoParams()
        {
            MethodCache cache = new MethodCache();
            var obj1 = cache.CreateInstance<Sample1>();

            obj1.Prop.Should().Be(0);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 创建委托
        /// </summary>
        /// <param name="service">继承NarutoWebSocketService的服务</param>
        /// <param name="action">执行的方法</param>
        /// <param name="parameterEntity">方法的参数</param>
        /// <param name="parameterType">参数类型</param>
        /// <param name="isParamter">是否为有参数的</param>
        /// <returns></returns>
        private static Task Create(object service, string action, bool isParamter, object parameterEntity, Type parameterType)
        {
            //定义输入参数
            var p1 = Expression.Parameter(service.GetType(), "service");
            //方法的参数对象
            var methodParameter = Expression.Parameter(isParamter ? parameterType : typeof(object), "methodParameter");

            //动态执行方法
            var methodCacheInfo = MethodCache.Get(service.GetType(), action);
            //调用指定的方法
            MethodCallExpression actionCall = null;

            //验证是否方法是否 有参数
            if (methodCacheInfo.ParameterInfos.Count() == 0)
            {
                //执行无参方法
                actionCall = Expression.Call(p1, methodCacheInfo.Method);
            }
            else
            {
                //执行有参的方法
                actionCall = Expression.Call(p1, methodCacheInfo.Method, methodParameter);
            }
            //生成lambda
            var lambda = Expression.Lambda(actionCall, new ParameterExpression[] { p1, methodParameter });
            //获取key
            var key = service.GetType().Name + action;

            //存储
            exec.TryAdd(key, lambda.Compile());

            return(exec[key].DynamicInvoke(service, parameterEntity) as Task);
        }
Exemplo n.º 12
0
        public void TestConstructorResolutionWith1StringParam()
        {
            MethodCache cache = new MethodCache();
            var obj1 = cache.CreateInstance<Sample1>("1");

            obj1.Prop.Should().Be(1);
        }
Exemplo n.º 13
0
        private static MethodInfoCollection GetMethodCollection(MethodCache cache, Type type, string name)
        {
            MethodInfoCollection info;

            if (!cache.TryGetValue(name, out info))
            {
                return(null);
            }
            return(info);
        }
Exemplo n.º 14
0
        public void Execute(Runner my)
        {
            var prop = typeof(TestClass).GetProperty("TestProperty");
            var obj  = new TestClass();

            my.Execute("raw", i =>
            {
                obj.TestProperty = "asd";
            });

            var stdDel = (Action <TestClass, string>)Delegate.CreateDelegate(typeof(Action <TestClass, string>), prop.GetSetMethod());

            my.Execute("stddel", i =>
            {
                stdDel(obj, "asd");
            });

            var genDel = new MethodCache().GetSetter(prop);

            my.Execute("gendel", i =>
            {
                genDel(obj, "asd");
            });

            var cache  = new MethodCache();
            var method = prop.GetSetMethod();

            cache.GetInvoker(method);
            my.Execute("gendelc", i =>
            {
                cache.GetInvoker(method)(obj, "asd");
            });

            my.Execute("gendelc2", i =>
            {
                cache.GetSetter(prop)(obj, "asd");
            });

            my.Execute("invoke", i =>
            {
                method.Invoke(obj, new[] { "asd" });
            });

            my.Execute("setvalue", i =>
            {
                prop.SetValue(obj, "asd", null);
            });

            var settable = prop.ToSettable();

            my.Execute("settable", i =>
            {
                settable.Set(obj, "asd");
            });
        }
Exemplo n.º 15
0
    MethodCache GetMethod(int opcode)
    {
        if (methods.ContainsKey(opcode))
        {
            return(methods[opcode]);
        }
        else
        {
            string method = Enum.GetName(opcodeType, opcode);
            if (string.IsNullOrEmpty(method) == false)
            {
                var m = commandType.GetMethod(method);

                if (m != null)
                {
                    var mc = new MethodCache();
                    methods[opcode] = mc;
                    mc.Method       = m;
                    var ps = m.GetParameters();

                    if (ps.Length == 1)
                    {
                        var po = Activator.CreateInstance(ps[0].ParameterType);
                        mc.ParameterType = ps[0].ParameterType;
                        var rm = ps[0].ParameterType.GetMethod("ReadFrom", new Type[] { typeof(byte[]), typeof(int), typeof(int) });
                        if (rm != null)
                        {
                            mc.ReadMethod = rm;
                        }
                        else
                        {
                            Debug.LogError("Command" + method + " 参数" + ps[0].ParameterType.FullName + "没有ReadFrom函数,无法执行");
                        }
                    }
                    else if (ps.Length >= 1)
                    {
                        Debug.LogError("Command" + method + " 参数个数大于1,无法执行");
                    }
                    return(mc);
                }
                else
                {
                    Debug.LogError("CommandHandle: " + method + " not found");
                    return(null);
                }
            }
            else
            {
                Debug.LogWarning(string.Format("收到未定义的ClientMethod opcode: {0}", opcode));
                return(null);
            }
        }
    }
Exemplo n.º 16
0
        /// <inheritdoc />
        protected internal override object Invoke(MethodInvocation invocation)
        {
            var targetMethod = MethodCache.GetMethodMap(TargetType, invocation.Method);
            var signature    = new InvocationSignature(
                invocation.Method, targetMethod, DeclaringType,
                TargetType, invocation.Method.GetInvocationType());

            return(Interceptor.Intercept(
                       signature, invocation.MethodCall,
                       invocation.Arguments, Target,
                       invocation.TransparentProxy));
        }
Exemplo n.º 17
0
        public static Subroutine OldEvalPopSubroutine <Local, Parameter, Type, Method, Field, Property, Attribute, Assembly>(
            MethodCache <Local, Parameter, Type, Method, Field, Property, Attribute, Assembly> methodCache,
            Subroutine oldEval
            )
        {
            Debug.Assert(oldEval.StackDelta == 1);
            var sub = new SimpleILCodeProvider <Local, Parameter, Type, Method, Field, Property, Attribute, Assembly>(
                new Instruction[] { Instruction.Pop },
                0).GetSubroutine(methodCache);

            sub.AddEdgeSubroutine(sub.Entry, sub.EntryAfterRequires, oldEval, "oldmanifest");
            return(sub);
        }
Exemplo n.º 18
0
        public void Execute(Runner my)
        {
            var prop = typeof(TestClass).GetProperty("TestProperty");
            var obj = new TestClass();

            my.Execute("raw", i =>
            {
                obj.TestProperty = "asd";
            });

            var stdDel = (Action<TestClass, string>)Delegate.CreateDelegate(typeof(Action<TestClass, string>), prop.GetSetMethod());
            my.Execute("stddel", i =>
            {
                stdDel(obj, "asd");
            });

            var genDel = new MethodCache().GetSetter(prop);
            my.Execute("gendel", i =>
            {
                genDel(obj, "asd");
            });

            var cache = new MethodCache();
            var method = prop.GetSetMethod();
            cache.GetInvoker(method);
            my.Execute("gendelc", i =>
            {
                cache.GetInvoker(method)(obj, "asd");
            });

            my.Execute("gendelc2", i =>
            {
                cache.GetSetter(prop)(obj, "asd");
            });

            my.Execute("invoke", i =>
            {
                method.Invoke(obj, new[] { "asd" });
            });

            my.Execute("setvalue", i =>
            {
                prop.SetValue(obj, "asd", null);
            });

            var settable = prop.ToSettable();
            my.Execute("settable", i =>
            {
                settable.Set(obj, "asd");
            });
        }
Exemplo n.º 19
0
        public ServiceMethod Resolve(InvocationTarget target)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target), "An invocation target must be specified.");
            }

            if (target.IsWeaklyTyped)
            {
                ServiceMethod[] methods;
                if (string.IsNullOrEmpty(target.TypeName))
                {
                    SimpleMethodCache.TryGetValue(target.MethodName, out methods);
                }
                else
                {
                    TypedMethodCache.TryGetValue(GetTypedMethodKey(target.TypeName, target.MethodName), out methods);
                }

                if (methods == null)
                {
                    throw new MissingMethodException("The specified request contains an unrecognized interface name, method name.");
                }

                if (methods.Length > 1)
                {
                    throw new ProgrammaticException("Weakly-typed requests cannot be used for methods with more than one overload (including methods that are only differentiated by letter case)",
                                                    unencrypted: new Tags {
                        { "method", target.MethodName }, { "type", target.TypeName }
                    });
                }

                return(methods.Single());
            }
            else
            {
                if (string.IsNullOrEmpty(target.TypeName) || string.IsNullOrEmpty(target.MethodName) || target.ParameterTypes == null)
                {
                    throw new ArgumentException("The specified invocation target is invalid.", nameof(target));
                }

                MethodCache.TryGetValue(target, out ServiceMethod method);

                if (method == null)
                {
                    throw new MissingMethodException("The specified request contains an unrecognized interface name, method name or method overload.");
                }

                return(method);
            }
        }
Exemplo n.º 20
0
        public void TestMethodCachedResult()
        {
            Type t = typeof(Sample1);
            MethodCache cache = new MethodCache();

            MethodInfo m1 = t.GetMethod("Method");
            InvocationDelegate d1 = cache.GetInvoker(m1);

            MethodInfo m2 = t.GetMethod("Method");
            InvocationDelegate d2 = cache.GetInvoker(m2);

            Assert.AreSame(m1, m2);
            Assert.AreSame(d1, d2);
        }
Exemplo n.º 21
0
        public void TestPropertySetCachedResult()
        {
            Type        t     = typeof(Sample1);
            MethodCache cache = new MethodCache();

            PropertyInfo       p1 = t.GetProperty("Prop");
            InvocationDelegate d1 = cache.GetSetter(p1);

            PropertyInfo       p2 = t.GetProperty("Prop");
            InvocationDelegate d2 = cache.GetSetter(p2);

            Assert.AreSame(p1, p2);
            Assert.AreSame(d1, d2);
        }
Exemplo n.º 22
0
        public void TestMethodCachedResult()
        {
            Type        t     = typeof(Sample1);
            MethodCache cache = new MethodCache();

            MethodInfo         m1 = t.GetMethod("Method");
            InvocationDelegate d1 = cache.GetInvoker(m1);

            MethodInfo         m2 = t.GetMethod("Method");
            InvocationDelegate d2 = cache.GetInvoker(m2);

            Assert.AreSame(m1, m2);
            Assert.AreSame(d1, d2);
        }
        public virtual ActionResult PurgeCache()
        {
            try
            {
                MethodCache.ExpireAll();
                QueryCacheManager.ExpireAll();
                SuccessNotification(_localizationService.GetResource("OperationCompletedSuccessfully"));
            }
            catch (Exception e)
            {
                ErrorNotification(e);
            }

            return(RedirectToAction("Index", "Administration"));
        }
Exemplo n.º 24
0
        /// <summary>
        /// 执行接收的外部消息
        /// </summary>
        /// <param name="service"></param>
        /// <param name="currentServiceType">当前上下文的类型</param>
        /// <param name="messageModel">消息模型</param>
        /// <returns></returns>
        private async Task EexecReciveMessage(object service, Type currentServiceType, WebSocketMessageModel messageModel)
        {
            //获取方法
            var methodCacheInfo = MethodCache.Get(currentServiceType, messageModel.action);
            //获取方法的参数
            var parameters = methodCacheInfo.ParameterInfos;

            //是否含有参数
            var isParamater = parameters.Count() > 0;
            //参数信息
            var parameterEntity = parameters.Count() > 0 ?await messageModel.message?.ToString().ToDeserializeAsync(parameters[0].ParameterType) : null;

            //执行操作
            await NarutoWebSocketServiceExpression.ExecAsync(service, messageModel.action, isParamter : isParamater, parameterEntity : parameterEntity, parameterType : isParamater?parameters[0].ParameterType : default).ConfigureAwait(false);
        }
Exemplo n.º 25
0
        public virtual async Task UpdateAsync(T record)
        {
            var oldRecord = await FindByIdAsync(record.Id);

            _dbContext.Set <T>().AddOrUpdate(record);
            await _dbContext.SaveChangesAsync();

            //Set Post Tags & Categories
            await UpdatePostTagsAsync(record.Id, record.Tags?.Select(p => p.Tag).ToList());
            await UpdatePostCategoriesAsync(record.Id, record.Categories?.Select(p => p.Id).ToList());

            QueryCacheManager.ExpireTag(_cacheKey);
            MethodCache.ExpireTag(_cacheKey);

            _eventPublisher.EntityUpdated(record, oldRecord);
        }
Exemplo n.º 26
0
 protected override void Activities(Fiber fiber)
 {
     manager = (IServicesManager)Managers.Find($"{serviceName}ServicesManager");
     if (manager == default)
     {
         Debug.LogError(Error = $"No service manager '{serviceName}ServicesManager' in a Managers game object");
     }
     else
     {
         fiber.OnError(exit: true, actor: message => Error = message).Do(Reset)
         .Begin
         .WaitFor(_ => MethodCache.Call(serviceAdapter, "Call", this) as Emitter)
         .Until(_ => (Error == null) || ((serviceAdapter = manager.Next()) == null))
         .If(_ => serviceAdapter == null).Error($"No Server '{serviceName} {entryPointName}' can Respond").End
         .Finish();
     }
 }
Exemplo n.º 27
0
        private static MethodCache GetMethodCache(Type type)
        {
            MethodCache result;

            if (!_tpyeCache.TryGetValue(type, out result))
            {
                lock (_tpyeCache)
                {
                    if (!_tpyeCache.TryGetValue(type, out result))
                    {
                        result           = new MethodCache();
                        _tpyeCache[type] = result;
                    }
                }
            }
            return(result);
        }
Exemplo n.º 28
0
        private static MethodInfoCollection GetMethodCollectionAndCache(InvokeContextBase context, Type type)
        {
            MethodCache          cache = GetMethodCache(type);
            MethodInfoCollection infos = GetMethodCollection(cache, type, context.MethodName);

            if (infos == null)
            {
                lock (_syncMethodObject)
                {
                    infos = GetMethodCollection(cache, type, context.MethodName);
                    if (infos == null)
                    {
                        infos = new MethodInfoCollection();
                        MemberInfo[] methods = type.GetMembers(_defaultBinding);
                        int          index   = 0;
                        if (methods != null && methods.Length > 0)
                        {
                            foreach (MemberInfo info in methods)
                            {
                                index++;
                                if (index < 0)
                                {
                                    break;
                                }
                                if (info.MemberType == MemberTypes.Method)
                                {
                                    MethodInfo      method = (MethodInfo)info;
                                    MethodAttribute attr   = GetMethodAttribute(method);
                                    if (attr != null && string.Compare(attr.MethodName, context.MethodName, true) == 0)
                                    {
                                        infos.Add(method);
                                    }
                                    else if (string.Compare(info.Name, context.MethodName, true) == 0)
                                    {
                                        infos.Add(method);
                                    }
                                }
                            }
                        }
                        cache[context.MethodName] = infos;
                    }
                }
            }
            return(infos);
        }
Exemplo n.º 29
0
 private static MethodInfo TryFindInterfaceMethodMatching(
     Type interfaceType,
     string methodName,
     Type returnType,
     Type[] parameterTypes)
 {
     lock (MethodCache)
     {
         PopulateMethodCacheIfNecessaryFor(interfaceType);
         return(MethodCache.TryGetValue(Tuple.Create(
                                            interfaceType,
                                            methodName,
                                            returnType,
                                            parameterTypes), out var result)
             ? result
             : null);
     }
 }
Exemplo n.º 30
0
        public BasicAnalysisDriver(
            IDecodeMetaData <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
            IDecodeContracts <Local, Parameter, Method, Field, Type> contractDecoder,
            IOutput output,
            LogOptions options
            )
        {
            Contract.Requires(mdDecoder != null);
            Contract.Requires(contractDecoder != null);
            Contract.Requires(output != null);
            Contract.Requires(options != null);

            this.methodCache     = new MethodCache <Local, Parameter, Type, Method, Field, Property, Event, Attribute, Assembly>(mdDecoder, contractDecoder, output.WriteLine);
            this.mdDecoder       = mdDecoder;
            this.contractDecoder = contractDecoder;
            this.output          = output;
            this.options         = options;
        }
Exemplo n.º 31
0
        private void InitializeInterface(TypeInfo interfaceType)
        {
            var members = interfaceType.DeclaredMembers;

            //check that we only have methods and no properties
            if (interfaceType.DeclaredMembers.Any(x => !(x is MethodInfo)))
            {
                throw new ArgumentException("The interface must only provide methods.", nameof(interfaceType));
            }

            //an interface without any methods is pointless
            var methods = members.Cast <MethodInfo>().ToList();

            if (methods.Count == 0)
            {
                throw new ArgumentException("The interface must at least provide one method.", nameof(interfaceType));
            }

            var dictionary = new Dictionary <MethodInfo, MethodCache>();

            foreach (var methodInfo in methods)
            {
                Type actualReturnType;
                if (methodInfo.ReturnType == typeof(Task))
                {
                    actualReturnType = null;
                }
                else if (methodInfo.ReturnType.GetTypeInfo().IsGenericType&&
                         methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(Task <>))
                {
                    actualReturnType = methodInfo.ReturnType.GenericTypeArguments[0];
                }
                else
                {
                    throw new ArgumentException("Only tasks are supported as return type.", methodInfo.ToString());
                }

                var methodCache = new MethodCache(methodInfo.GetMethodId(), actualReturnType,
                                                  methodInfo.GetParameters().Select(x => x.ParameterType).ToArray());
                dictionary.Add(methodInfo, methodCache);
            }

            _methods = dictionary;
        }
Exemplo n.º 32
0
        public virtual async Task DeleteAsync(int id)
        {
            var record = await FindByIdAsync(id);

            await _userLikesService.DeletePostLikesAsync(id);

            await _userWishlistService.DeletePostFromWishlistAsync(id);

            await _dbContext.PostComments.Where(p => p.PostId == id).DeleteAsync();

            var post = await FindByIdAsync(id);

            _dbContext.Set <T>().Remove(post);
            await _dbContext.SaveChangesAsync();

            await _localizedEntityService.DeleteEntityAllLocalizedStringsAsync(typeof(T).Name, id);

            QueryCacheManager.ExpireTag(_cacheKey);
            MethodCache.ExpireTag(_cacheKey);

            _eventPublisher.EntityDeleted(record);
        }
Exemplo n.º 33
0
        public virtual async Task <int> AddAsync(T record)
        {
            var postTags       = record.Tags?.Select(p => p.Tag).ToList();
            var postCategories = record.Categories?.Select(p => p.Id).ToList();

            record.Tags       = null;
            record.Categories = null;

            _dbContext.Set <T>().Add(record);
            await _dbContext.SaveChangesAsync();

            //Set Post Tags & Categories
            await UpdatePostTagsAsync(record.Id, postTags);
            await UpdatePostCategoriesAsync(record.Id, postCategories);

            QueryCacheManager.ExpireTag(_cacheKey);
            MethodCache.ExpireTag(_cacheKey);

            _eventPublisher.EntityInserted(record);

            return(record.Id);
        }
Exemplo n.º 34
0
 public void TestConstructorResolutionWith2IntParamWhenOneIsNull()
 {
     MethodCache cache = new MethodCache();
     var obj = cache.CreateInstance<Sample1>(BindingFlags.NonPublic | BindingFlags.Instance, 1, null);
     obj.Prop.Should().Be(1);
 }
Exemplo n.º 35
0
        private async Task <object> SendMethodCall(MethodCache methodCache, object[] parameters)
        {
            if (methodCache == null)
            {
                throw new ArgumentException("The parameter cannot be null.", nameof(methodCache));
            }
            if (methodCache == null)
            {
                throw new ArgumentException("The parameter cannot be null.", nameof(parameters));
            }

            //PROTOCOL
            //CALL:
            //HEAD      - 4 bytes                   - Identifier, ASCII (NTC1)
            //HEAD      - integer                   - callback identifier
            //HEAD      - uinteger                  - The method identifier
            //HEAD      - integer * parameters      - the length of each parameter
            //--------------------------------------------------------------------------
            //DATA      - length of the parameters  - serialized parameters

            var callbackId = (uint)Interlocked.Increment(ref _callIdCounter);

            var buffer = new byte[CustomOffset /* user offset */ + 4 /* Header */ + 4 /* Callback id */ +
                                  4 /* method id */ + parameters.Length * 4 /* parameter meta */ +
                                  EstimatedDataPerParameter * parameters.Length /* parameter data */];
            var bufferOffset = CustomOffset + 12 + parameters.Length * 4;

            for (var i = 0; i < parameters.Length; i++)
            {
                var metaOffset      = CustomOffset + 12 + i * 4;
                var parameterLength = _serializer.Serialize(methodCache.ParameterTypes[i],
                                                            ref buffer, bufferOffset, parameters[i]);
                Buffer.BlockCopy(BitConverter.GetBytes(parameterLength), 0, buffer, metaOffset, 4);

                bufferOffset += parameterLength;
            }

            //write header
            buffer[CustomOffset]     = CallProtocolInfo.Header1;
            buffer[CustomOffset + 1] = CallProtocolInfo.Header2;
            buffer[CustomOffset + 2] = CallProtocolInfo.Header3Call;
            buffer[CustomOffset + 3] = CallProtocolInfo.Header4;

            //write callback id
            Buffer.BlockCopy(BitConverter.GetBytes(callbackId), 0, buffer, CustomOffset + 4, 4);

            //method identifier
            Buffer.BlockCopy(BitConverter.GetBytes(methodCache.MethodId), 0, buffer, CustomOffset + 8, 4);

            var callback     = new ResultCallback();
            var callbackWait = callback.Wait(WaitTimeout);

            _callbacks.TryAdd(callbackId, callback);                               //impossible that this goes wrong

            OnSendData(new ArraySegment <byte>(buffer, 0, bufferOffset)).Forget(); //no need to await that

            using (callback)
            {
                if (!await callbackWait.ConfigureAwait(false))
                {
                    _callbacks.TryRemove(callbackId, out var _);
                    throw new TimeoutException("The method call timed out, no response received.");
                }

                switch (callback.ResponseType)
                {
                case CallTransmissionResponseType.MethodExecuted:
                    return(null);

                case CallTransmissionResponseType.ResultReturned:
                    return(_serializer.Deserialize(methodCache.ReturnType, callback.Data,
                                                   callback.Offset));

                case CallTransmissionResponseType.Exception:
                    var up = _serializer.DeserializeException(callback.Data, callback.Offset);
                    throw up;

                case CallTransmissionResponseType.MethodNotImplemented:
                    throw new NotImplementedException("The remote method is not implemented.");

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
Exemplo n.º 36
0
        /*
         * Matches a method against its arguments in the Lua stack. Returns
         * if the match was succesful. It it was also returns the information
         * necessary to invoke the method.
         */
        internal bool matchParameters(LuaCore.lua_State luaState, MethodBase method, ref MethodCache methodCache)
        {
            ExtractValue extractValue;
            bool isMethod = true;
            var paramInfo = method.GetParameters();
            int currentLuaParam = 1;
            int nLuaParams = LuaLib.lua_gettop(luaState);
            var paramList = new ArrayList();
            var outList = new List<int>();
            var argTypes = new List<MethodArgs>();

            foreach(var currentNetParam in paramInfo)
            {
                if(!currentNetParam.IsIn && currentNetParam.IsOut)  // Skips out params
                    outList.Add(paramList.Add(null));
                else if(currentLuaParam > nLuaParams) // Adds optional parameters
                {
                    if(currentNetParam.IsOptional)
                        paramList.Add(currentNetParam.DefaultValue);
                    else
                    {
                        isMethod = false;
                        break;
                    }
                }
                else if(_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue))  // Type checking
                {
                    int index = paramList.Add(extractValue(luaState, currentLuaParam));
                    var methodArg = new MethodArgs();
                    methodArg.index = index;
                    methodArg.extractValue = extractValue;
                    argTypes.Add(methodArg);

                    if(currentNetParam.ParameterType.IsByRef)
                        outList.Add(index);

                    currentLuaParam++;
                }  // Type does not match, ignore if the parameter is optional
                else if(_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue))
                {
                    object luaParamValue = extractValue(luaState, currentLuaParam);
                    var paramArrayType = currentNetParam.ParameterType.GetElementType();
                    Array paramArray;

                    if(luaParamValue is LuaTable)
                    {
                        var table = (LuaTable)luaParamValue;
                        var tableEnumerator = table.GetEnumerator();
                        paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
                        tableEnumerator.Reset();
                        int paramArrayIndex = 0;

                        while(tableEnumerator.MoveNext())
                        {
                            paramArray.SetValue(Convert.ChangeType(tableEnumerator.Value, currentNetParam.ParameterType.GetElementType()), paramArrayIndex);
                            paramArrayIndex++;
                        }
                    }
                    else
                    {
                        paramArray = Array.CreateInstance(paramArrayType, 1);
                        paramArray.SetValue(luaParamValue, 0);
                    }

                    int index = paramList.Add(paramArray);
                    var methodArg = new MethodArgs();
                    methodArg.index = index;
                    methodArg.extractValue = extractValue;
                    methodArg.isParamsArray = true;
                    methodArg.paramsArrayType = paramArrayType;
                    argTypes.Add(methodArg);
                    currentLuaParam++;
                }
                else if(currentNetParam.IsOptional)
                    paramList.Add(currentNetParam.DefaultValue);
                else  // No match
                {
                    isMethod = false;
                    break;
                }
            }

            if(currentLuaParam != nLuaParams + 1) // Number of parameters does not match
                isMethod = false;
            if(isMethod)
            {
                methodCache.args = paramList.ToArray();
                methodCache.cachedMethod = method;
                methodCache.outList = outList.ToArray();
                methodCache.argTypes = argTypes.ToArray();
            }

            return isMethod;
        }
Exemplo n.º 37
0
        /*
         * __call metafunction of type references. Searches for and calls
         * a constructor for the type. Returns nil if the constructor is not
         * found or if the arguments are invalid. Throws an error if the constructor
         * generates an exception.
         */
        private int callConstructor(LuaCore.lua_State luaState)
        {
            var validConstructor = new MethodCache();
            IReflect klass;
            object obj = translator.getRawNetObject(luaState, 1);

            if(obj.IsNull() || !(obj is IReflect))
            {
                translator.throwError(luaState, "trying to call constructor on an invalid type reference");
                LuaLib.lua_pushnil(luaState);
                return 1;
            }
            else
                klass = (IReflect)obj;

            LuaLib.lua_remove(luaState, 1);
            var constructors = klass.UnderlyingSystemType.GetConstructors();

            foreach(var constructor in constructors)
            {
                bool isConstructor = matchParameters(luaState, constructor, ref validConstructor);

                if(isConstructor)
                {
                    try
                    {
                        translator.push(luaState, constructor.Invoke(validConstructor.args));
                    }
                    catch(TargetInvocationException e)
                    {
                        ThrowError(luaState, e);
                        LuaLib.lua_pushnil(luaState);
                    }
                    catch
                    {
                        LuaLib.lua_pushnil(luaState);
                    }

                    return 1;
                }
            }

            string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name;
            translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match",
                klass.UnderlyingSystemType, constructorName));
            LuaLib.lua_pushnil(luaState);
            return 1;
        }
 public Subroutine GetSubroutine(MethodCache <Local, Parameter, Type, Method, Field, Property, Event, Attribute, Assembly> methodCache)
 {
     Contract.Requires(methodCache != null); // F: Added as of Clousot suggestion
     return(methodCache.BuildSubroutine(stackDelta, this, 0));
 }
		/// <summary>
		/// Initializes a new instance of the CachingHandler class.
		/// </summary>
		/// <param name="container">The Unity Container.</param>
		public CachingHandler(IUnityContainer container)
		{
			this.cache = container.Resolve<MethodCache>();
		}
Exemplo n.º 40
0
 public void TestConstructorThatDoesntExist()
 {
     MethodCache cache = new MethodCache();
     Assert.Throws<MissingMethodException>(()=>
             cache.CreateInstance<Sample1>("asd", null, 1));
 }
Exemplo n.º 41
0
 /*
  * Checks if the method matches the arguments in the Lua stack, getting
  * the arguments if it does.
  */
 internal bool matchParameters(LuaCore.lua_State luaState, MethodBase method, ref MethodCache methodCache)
 {
     return metaFunctions.matchParameters(luaState, method, ref methodCache);
 }
Exemplo n.º 42
0
 public void TestConstructorResolutionWith1StringWrongParam()
 {
     MethodCache cache = new MethodCache();
     Assert.Throws<FormatException>(() =>
             cache.CreateInstance<Sample1>("a"));
 }
Exemplo n.º 43
0
        public void TestPropertyGetCachedResult()
        {
            Type t = typeof(Sample1);
            MethodCache cache = new MethodCache();

            PropertyInfo p1 = t.GetProperty("Prop");
            InvocationDelegate d1 = cache.GetGetter(p1);

            PropertyInfo p2 = t.GetProperty("Prop");
            InvocationDelegate d2 = cache.GetGetter(p2);

            Assert.AreSame(p1, p2);
            Assert.AreSame(d1, d2);
        }