Beispiel #1
0
        /************************************************************************/
        /* NAVIGATE                                                             */
        /************************************************************************/
        //! move into next pipeline
#if TEST
        public PipelineDescriptor NavigatePush(int moduleIdx)
        {
            ImportContext impctx = new ImportContext();

            impctx.Register(new ListImporter <ModuleDescriptor>());
            impctx.Register(new ListImporter <ConnectionDescriptor>());
            impctx.Register(new ListImporter <EndpointDescriptor>());

            PipelineDescriptor newPipeline = ((Response <PipelineDescriptor>)impctx.Import(
                                                  typeof(Response <PipelineDescriptor>),
                                                  JsonText.CreateReader(test_Pipeline1JSON))).GetResponse();

            NuiState.Instance.level++;
            currentPipeline = newPipeline;

            return(newPipeline);
        }
        public void ConstructionWithTail()
        {
            ObjectConstructor        ctor    = new ObjectConstructor(typeof(Point));
            ImportContext            context = JsonConvert.CreateImportContext();
            const string             json    = "{ y: 456, z: 789, x: 123 }";
            ObjectConstructionResult result  = ctor.CreateObject(context, JsonText.CreateReader(json));
            Point point = (Point)result.Object;

            Assert.AreEqual(123, point.X);
            Assert.AreEqual(456, point.Y);
            NamedJsonBuffer[] tail = JsonBuffer.From(result.TailReader).GetMembersArray();
            Assert.AreEqual(1, tail.Length);
            NamedJsonBuffer z = tail[0];

            Assert.AreEqual("z", z.Name);
            Assert.AreEqual(789, z.Buffer.GetNumber().ToInt32());
        }
Beispiel #3
0
 public virtual object Invoke(Type returnType, string method, object args)
 {
     if (method == null)
     {
         throw new ArgumentNullException("method");
     }
     if (method.Length == 0)
     {
         throw new ArgumentException(null, "method");
     }
     if (returnType == null)
     {
         throw new ArgumentNullException("returnType");
     }
     try
     {
         var request = GetWebRequest(new Uri(Url));
         request.Method = "POST";
         var utf8EmitBom = new UTF8Encoding(false);
         using (var stream = request.GetRequestStream())
             using (var writer = new StreamWriter(stream, utf8EmitBom))
             {
                 var call = new JsonObject();
                 call["id"]      = ++_id;
                 call["jsonrpc"] = "2.0";
                 call["method"]  = method;
                 if (args != null)
                 {
                     call["params"] = args;
                 }
                 JsonConvert.Export(call, writer);
             }
         object ret;
         using (var response = GetWebResponse(request))
             using (var stream = response.GetResponseStream())
                 using (var reader = new StreamReader(stream, Encoding.UTF8))
                     ret = OnResponse(JsonText.CreateReader(reader), returnType);
         return(ret);
     }
     catch (WebException ex)
     {
         throw new JsonException("Invalid JSON-RPC response. It contains neither a result nor error : " + ex.Message);
     }
 }
Beispiel #4
0
        public virtual object Invoke(Type returnType, string method, object args)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }
            if (method.Length == 0)
            {
                throw new ArgumentException(null, "method");
            }
            if (returnType == null)
            {
                throw new ArgumentNullException("returnType");
            }

            WebRequest request = GetWebRequest(new Uri(Url));

            request.Method = "POST";

            Encoding requestEncoding = RequestEncoding;

            if (requestEncoding == null)
            {
                requestEncoding = new UTF8Encoding(false);
            }

            request.ContentType = RequestMediaType
                                  + "; charset=" + requestEncoding.HeaderName;

            using (Stream stream = request.GetRequestStream())
                using (StreamWriter writer = new StreamWriter(stream, requestEncoding))
                {
                    JsonObject call = new JsonObject();
                    call["id"]     = ++_id;
                    call["method"] = method;
                    call["params"] = args != null ? args : _zeroArgs;
                    JsonConvert.Export(call, writer);
                }

            using (WebResponse response = GetWebResponse(request))
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        return(OnResponse(JsonText.CreateReader(reader), returnType));
        }
Beispiel #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <exception cref="ArgumentNullException">строка запроса не может быть равна null</exception>
        /// <exception cref="ArgumentException">json request некорректен по формату</exception>
        public JsonRequest(string request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (request.Length == 0)
            {
                throw new ArgumentException(null, "request");
            }

            mRequest = request;
            Args     = null;

            // parse request here
            var reader  = JsonText.CreateReader(mRequest);
            var members = JsonBuffer.From(reader).GetMembersArray();

            foreach (var member in members)
            {
                switch (member.Name)
                {
                case "id":
                    Id = (long)JsonConvert.Import(typeof(long), member.Buffer.CreateReader());
                    break;

                case "method":
                    Method = (string)JsonConvert.Import(typeof(string), member.Buffer.CreateReader());
                    break;

                case "params":
                    Args = JsonConvert.Import(typeof(object), member.Buffer.CreateReader());
                    break;
                }
            }

            if (Method.Length == 0)
            {
                throw new ArgumentException("method");
            }
        }
        private static object Import(bool hasValue, string input)
        {
            JsonReader    reader        = JsonText.CreateReader(input);
            ImportContext context       = JsonConvert.CreateImportContext();
            ThingImporter thingImporter = new ThingImporter();

            context.Register(thingImporter);
            NullableImporter importer = new NullableImporter(typeof(Thing?));
            object           thing    = importer.Import(context, reader);

            Assert.AreEqual(hasValue, thingImporter.ImportCalled);
            if (hasValue)
            {
                Assert.IsInstanceOfType(typeof(Thing), thing);
            }
            else
            {
                Assert.IsNull(thing);
            }
            Assert.IsTrue(reader.EOF, "Reader must be at EOF.");
            return(thing);
        }
 public void CannotImportWithNullContext()
 {
     new JsonBufferImporter().Import(null, JsonText.CreateReader(string.Empty));
 }
        public void ValueTypeWithDefaultConstructorConstruction()
        {
            ObjectConstructor        constructor = new ObjectConstructor(typeof(ValueThing));
            ObjectConstructionResult result      = constructor.CreateObject(new ImportContext(), JsonText.CreateReader("{foo:bar}"));

            Assert.IsInstanceOfType(typeof(ValueThing), result.Object);
            JsonReader tail = result.TailReader;

            tail.ReadToken(JsonTokenClass.Object);
            Assert.AreEqual("foo", tail.ReadMember());
            Assert.AreEqual("bar", tail.ReadString());
            tail.ReadToken(JsonTokenClass.EndObject);
        }
Beispiel #9
0
        private static void Run()
        {
            ImportContext impctx = new ImportContext();

            //
            // Import a strongly-typed collection of integers...
            //

            impctx.Register(new ListImporter <int>());

            List <int> numbers = (List <int>)impctx.Import(typeof(List <int>),
                                                           JsonText.CreateReader("[ 1, 2, 3 ]"));

            numbers.ForEach(Console.WriteLine);
            Console.WriteLine();

            //
            // Import a Shape object containing a strongly-typed collection of
            // Point objects.
            //

            impctx.Register(new ListImporter <Point>());

            Shape shape = (Shape)impctx.Import(typeof(Shape), JsonText.CreateReader(@"{ 
                    name: 'square', 
                    points: [
                        { x: 10, y: 10 },
                        { x: 20, y: 10 }, 
                        { x: 20, y: 20 },
                        { x: 10, y: 20 }
                    ]
                }"));

            JsonConvert.Export(shape, CreatePrettyWriter(Console.Out));
            Console.WriteLine();

            //
            // Import CookieCollection using duck-typing. In other words,
            // as long as CookieCollection walks and quacks like a
            // collection of Cookie elements then it's good enough for
            // DuckCollectionImporter. DuckCollectionImporter can infer
            // that CookieCollection contains Cookie elements.
            //

            impctx.Register(new DuckCollectionImporter(typeof(CookieCollection)));

            const string cookiesText = @"[
                    { name: 'one',   value: 1, expires: '2099-01-02' },
                    { name: 'two',   value: 2, expires: '2088-03-04' },
                    { name: 'three', value: 3, expires: '2077-05-06' }
                ]";

            CookieCollection cookies = (CookieCollection)impctx.Import(typeof(CookieCollection), JsonText.CreateReader(cookiesText));

            JsonConvert.Export(cookies, CreatePrettyWriter(Console.Out));
            Console.WriteLine();

            //
            // Now repeat, but replace with a new CookieCollection importer
            // that is identical in behavior but based on generics. Here,
            // the difference is that DuckCollectionImporter<,> does not
            // have to guess the element type as it is provided as a type
            // argument.
            //

            impctx.Register(new DuckCollectionImporter <CookieCollection, Cookie>());
            cookies = (CookieCollection)impctx.Import(typeof(CookieCollection), JsonText.CreateReader(cookiesText));
            JsonConvert.Export(cookies, CreatePrettyWriter(Console.Out));
            Console.WriteLine();

            //
            // Those Cookie objects have a lot of properties. Say our JSON
            // text only needs a subset. Here, we register an exporter that
            // provides a custom view of the type. We only expose the name,
            // value and expiration time. What's more, we rename the
            // Expires property so that it appears as "expiration" in JSON.
            //

            ExportContext expctx = new ExportContext();

            JsonType.
            BuildFor(typeof(Cookie)).
            AddProperty("Name").
            AddProperty("Value").
            AddProperty("Expires").As("expiration").
            Register(expctx);

            expctx.Export(cookies, CreatePrettyWriter(Console.Out));
            Console.WriteLine();
        }
Beispiel #10
0
 public static object Import(Type type, TextReader reader)
 {
     return(Import(type, JsonText.CreateReader(reader)));
 }
Beispiel #11
0
        public ResponseParser(string response, Type returnType)
        {
            if (returnType == null)
            {
                throw new ArgumentNullException("returnType");
            }
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            if (response.Length == 0)
            {
                throw new ArgumentException(null, "response");
            }


            var reader          = JsonText.CreateReader(response);
            var resultSpecified = false;

            mResult       = null;
            mErrorMessage = null;

            //
            // JSON-RPC 2.0 specification/protocol, states that either error
            // or result must be present but not both. JSON-RPC 1.0 is less
            // strict and states that one or the other must be null. There
            // is an ambiguity however with 1.0 when both result and error
            // are null. Here, it is treated like a successful null result.
            //

            var members = JsonBuffer.From(reader).GetMembersArray();

            foreach (var member in members)
            {
                switch (member.Name)
                {
                case "error":
                {
                    var errorObject = JsonConvert.Import(member.Buffer.CreateReader());
                    if (errorObject != null)
                    {
                        OnError(errorObject);
                    }
                }
                break;

                case "id":
                    Id = (string)JsonConvert.Import(typeof(string), member.Buffer.CreateReader());
                    break;

                case "result":
                {
                    resultSpecified = true;

                    mResult = (returnType != typeof(JsonBuffer))
                                          ? JsonConvert.Import(returnType, member.Buffer.CreateReader())
                                          : response;
                }
                break;
                }
            }

            if (!resultSpecified) // never gets here on error
            {
                throw new Exception("Invalid JSON-RPC response. It contains neither a result nor an error.");
            }
        }