Beispiel #1
0
        public Message HandleRequest(Message request)
        {
            string json = request.GetBody();

            System.Exception error  = null;
            object           result = null;

            string    method = null;
            ArrayList args   = null;

            MethodInstance target = null;

            Dictionary <string, object> parsed = null;

            try
            {
                parsed = (Dictionary <string, object>)JSON.Instance.Parse(json);
            }
            catch (System.Exception ex)
            {
                error = ex;
            }
            if (error == null)
            {
                try
                {
                    method = (string)parsed["method"];
                    args   = (ArrayList)parsed["params"];
                }
                catch (System.Exception ex)
                {
                    error = ex;
                }
                if (method == null)
                {
                    error = new ZbusException("missing method name");
                }
            }

            if (error == null)
            {
                if (this.methods.ContainsKey(method))
                {
                    target = this.methods[method];
                }
                else
                {
                    error = new ZbusException(method + " not found");
                }
            }

            if (error == null)
            {
                try
                {
                    ParameterInfo[] pinfo = target.Method.GetParameters();
                    if (pinfo.Length == args.Count)
                    {
                        object[] paras = new object[args.Count];
                        for (int i = 0; i < pinfo.Length; i++)
                        {
                            paras[i] = System.Convert.ChangeType(args[i], pinfo[i].ParameterType);
                        }
                        result = target.Method.Invoke(target.Instance, paras);
                    }
                    else
                    {
                        error = new ZbusException("number of argument not match");
                    }
                }
                catch (System.Exception ex)
                {
                    error = ex;
                }
            }

            Dictionary <string, object> data = new Dictionary <string, object>();

            if (error == null)
            {
                data["error"]  = null;
                data["result"] = result;
            }
            else
            {
                data["error"]  = error.Message;
                data["result"] = null;
            }

            string  resJson = JSON.Instance.ToJSON(data);
            Message res     = new Message();

            res.SetBody(resJson);

            return(res);
        }