Example #1
0
        public void CoreSerializeRequestWhenRequestIsNull()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();

            Assert.Throws <ArgumentNullException>(() =>
                                                  jsonRpcSerializer.SerializeRequest(null));
        }
Example #2
0
        public void V2SpecT021DeserializeRequest()
        {
            var jsonSample        = EmbeddedResourceManager.GetString("Assets.v2_spec_02.1_req.json");
            var jsonRpcSerializer = new JsonRpcSerializer();

            var jsonRpcSubtractParametersScheme = new Dictionary <string, Type>
            {
                ["subtrahend"] = typeof(long),
                ["minuend"]    = typeof(long)
            };

            jsonRpcSerializer.RequestContracts["subtract"] = new JsonRpcRequestContract(jsonRpcSubtractParametersScheme);

            var jsonRpcData = jsonRpcSerializer.DeserializeRequestData(jsonSample);

            Assert.False(jsonRpcData.IsBatch);

            var jsonRpcItem = jsonRpcData.Item;

            Assert.True(jsonRpcItem.IsValid);

            var jsonRpcMessage = jsonRpcItem.Message;

            Assert.Equal(4L, jsonRpcMessage.Id);
            Assert.Equal("subtract", jsonRpcMessage.Method);
            Assert.Equal(JsonRpcParametersType.ByName, jsonRpcMessage.ParametersType);
            Assert.Equal(23L, jsonRpcMessage.ParametersByName["subtrahend"]);
            Assert.Equal(42L, jsonRpcMessage.ParametersByName["minuend"]);
        }
Example #3
0
        public void V1SpecT010DeserializeRequest()
        {
            var jsonSample = EmbeddedResourceManager.GetString("Assets.v1_spec_01.0_req.json");

            var jsonRpcSerializer = new JsonRpcSerializer
            {
                CompatibilityLevel = JsonRpcCompatibilityLevel.Level1
            };

            jsonRpcSerializer.RequestContracts["echo"] = new JsonRpcRequestContract(new[] { typeof(string) });

            var jsonRpcData = jsonRpcSerializer.DeserializeRequestData(jsonSample);

            Assert.False(jsonRpcData.IsBatch);

            var jsonRpcItem = jsonRpcData.Item;

            Assert.True(jsonRpcItem.IsValid);

            var jsonRpcMessage = jsonRpcItem.Message;

            Assert.Equal(1L, jsonRpcMessage.Id);
            Assert.Equal("echo", jsonRpcMessage.Method);
            Assert.Equal(JsonRpcParametersType.ByPosition, jsonRpcMessage.ParametersType);
            Assert.Equal(new object[] { "Hello JSON-RPC" }, jsonRpcMessage.ParametersByPosition);
        }
Example #4
0
        public void V1SpecT010DeserializeResponse()
        {
            var jsonSample = EmbeddedResourceManager.GetString("Assets.v1_spec_01.0_res.json");

            var jsonRpcSerializer = new JsonRpcSerializer
            {
                CompatibilityLevel = JsonRpcCompatibilityLevel.Level1
            };

            jsonRpcSerializer.ResponseContracts["echo"]  = new JsonRpcResponseContract(typeof(string));
            jsonRpcSerializer.StaticResponseBindings[1L] = "echo";

            var jsonRpcData = jsonRpcSerializer.DeserializeResponseData(jsonSample);

            Assert.False(jsonRpcData.IsBatch);

            var jsonRpcItem = jsonRpcData.Item;

            Assert.True(jsonRpcItem.IsValid);

            var jsonRpcMessage = jsonRpcItem.Message;

            Assert.Equal(1L, jsonRpcMessage.Id);
            Assert.IsType <string>(jsonRpcMessage.Result);
            Assert.Equal("Hello JSON-RPC", jsonRpcMessage.Result);
        }
Example #5
0
        public void V1BitcoinT01DeserializeResponse()
        {
            var jsonSample = EmbeddedResourceManager.GetString("Assets.v1_btc_01_res.json");

            var jsonRpcSerializer = new JsonRpcSerializer
            {
                CompatibilityLevel = JsonRpcCompatibilityLevel.Level1
            };

            jsonRpcSerializer.ResponseContracts["getblockhash"] = new JsonRpcResponseContract(typeof(string));
            jsonRpcSerializer.StaticResponseBindings["foo"]     = "getblockhash";

            var jsonRpcData = jsonRpcSerializer.DeserializeResponseData(jsonSample);

            Assert.False(jsonRpcData.IsBatch);

            var jsonRpcItem = jsonRpcData.Item;

            Assert.True(jsonRpcItem.IsValid);

            var jsonRpcMessage = jsonRpcItem.Message;

            Assert.Equal("foo", jsonRpcMessage.Id);
            Assert.IsType <string>(jsonRpcMessage.Result);
            Assert.Equal("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f", jsonRpcMessage.Result);
        }
Example #6
0
        public void CoreSerializeResponsesWhenCollectionIsNull()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();

            Assert.Throws <ArgumentNullException>(() =>
                                                  jsonRpcSerializer.SerializeResponses(null));
        }
Example #7
0
        public void V1CoreDeserializeResponseWhenErrorTypeIsInvali()
        {
            var jsonSample = EmbeddedResourceManager.GetString("Assets.v1_core_error_type_invalid.json");

            var jsonRpcSerializer = new JsonRpcSerializer
            {
                CompatibilityLevel = JsonRpcCompatibilityLevel.Level1
            };

            jsonRpcSerializer.ResponseContracts["m"]     = new JsonRpcResponseContract(typeof(string));
            jsonRpcSerializer.StaticResponseBindings[1L] = "m";

            var jsonRpcData = jsonRpcSerializer.DeserializeResponseData(jsonSample);

            Assert.False(jsonRpcData.IsBatch);

            var jsonRpcItem = jsonRpcData.Item;

            Assert.True(jsonRpcItem.IsValid);

            var jsonRpcMessage = jsonRpcItem.Message;

            Assert.False(jsonRpcMessage.Success);
            Assert.Equal(1L, jsonRpcMessage.Id);
            Assert.Null(jsonRpcMessage.Result);
            Assert.NotNull(jsonRpcMessage.Error);

            var jsonRpcError = jsonRpcMessage.Error;

            Assert.Equal(default, jsonRpcError.Code);
Example #8
0
        public void V1BitcoinT02DeserializeResponse()
        {
            var jsonSample = EmbeddedResourceManager.GetString("Assets.v1_btc_02_res.json");

            var jsonRpcSerializer = new JsonRpcSerializer
            {
                CompatibilityLevel = JsonRpcCompatibilityLevel.Level1
            };

            jsonRpcSerializer.ResponseContracts["getblockhash"] = new JsonRpcResponseContract(typeof(string));
            jsonRpcSerializer.StaticResponseBindings["foo"]     = "getblockhash";

            var jsonRpcData = jsonRpcSerializer.DeserializeResponseData(jsonSample);

            Assert.False(jsonRpcData.IsBatch);

            var jsonRpcItem = jsonRpcData.Item;

            Assert.True(jsonRpcItem.IsValid);

            var jsonRpcMessage = jsonRpcItem.Message;

            Assert.Equal("foo", jsonRpcMessage.Id);
            Assert.False(jsonRpcMessage.Success);

            var jsonRpcError = jsonRpcMessage.Error;

            Assert.Equal(-8L, jsonRpcError.Code);
            Assert.Equal("Block height out of range", jsonRpcError.Message);
        }
Example #9
0
        public void V1BitcoinT01DeserializeRequest()
        {
            var jsonSample = EmbeddedResourceManager.GetString("Assets.v1_btc_01_req.json");

            var jsonRpcSerializer = new JsonRpcSerializer
            {
                CompatibilityLevel = JsonRpcCompatibilityLevel.Level1
            };

            jsonRpcSerializer.RequestContracts["getblockhash"] = new JsonRpcRequestContract(new[] { typeof(long) });

            var jsonRpcData = jsonRpcSerializer.DeserializeRequestData(jsonSample);

            Assert.False(jsonRpcData.IsBatch);

            var jsonRpcItem = jsonRpcData.Item;

            Assert.True(jsonRpcItem.IsValid);

            var jsonRpcMessage = jsonRpcItem.Message;

            Assert.Equal("foo", jsonRpcMessage.Id);
            Assert.Equal("getblockhash", jsonRpcMessage.Method);
            Assert.Equal(JsonRpcParametersType.ByPosition, jsonRpcMessage.ParametersType);
            Assert.Equal(new object[] { 0L }, jsonRpcMessage.ParametersByPosition);
        }
Example #10
0
        public void CoreDeserializeResponseDataWhenJsonStringIsNull()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();

            Assert.Throws <ArgumentNullException>(() =>
                                                  jsonRpcSerializer.DeserializeResponseData(null));
        }
            private PipeReader CreateReader(DataItem[] data)
            {
                var outputData = data
                                 .Select <DataItem, object>(
                    z =>
                {
                    if (z.MsgKind.EndsWith("response"))
                    {
                        return(new OutgoingResponse(z.MsgId, z.Arg, new Request(z.MsgId, z.MsgType, JValue.CreateNull())));
                    }

                    if (z.MsgKind.EndsWith("request"))
                    {
                        return(new OutgoingRequest
                        {
                            Id = z.MsgId,
                            Method = z.MsgType,
                            Params = z.Arg
                        });
                    }

                    if (z.MsgKind.EndsWith("notification"))
                    {
                        return(new OutgoingNotification
                        {
                            Method = z.MsgType,
                            Params = z.Arg
                        });
                    }

                    throw new NotSupportedException("unknown message kind " + z.MsgKind);
                }
                    );

                var pipeIn = new Pipe();

                var serializer = new JsonRpcSerializer();

                Task.Run(
                    async() =>
                {
                    foreach (var item in outputData)
                    {
                        var content      = serializer.SerializeObject(item);
                        var contentBytes = Encoding.UTF8.GetBytes(content).AsMemory();

                        await pipeIn.Writer.WriteAsync(
                            Encoding.UTF8.GetBytes($"Content-Length: {contentBytes.Length}\r\n\r\n")
                            );
                        await pipeIn.Writer.WriteAsync(contentBytes);
                        await pipeIn.Writer.FlushAsync();
                    }

                    await pipeIn.Writer.CompleteAsync();
                }
                    );


                return(pipeIn.Reader);
            }
        public async Task SerializeRequestAsyncWhenRequestIsNull()
        {
            var jrs = new JsonRpcSerializer();

            await Assert.ThrowsExceptionAsync <ArgumentNullException>(() =>
                                                                      jrs.SerializeRequestAsync(null, default).AsTask());
        }
Example #13
0
        public async void CoreDeserializeResponseDataAsyncFromStreamWhenJsonStreamIsNull()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();

            await Assert.ThrowsAsync <ArgumentNullException>(() =>
                                                             jsonRpcSerializer.DeserializeResponseDataAsync((Stream)null));
        }
Example #14
0
        public void V2CoreDeserializeResponseDataWhenHasDataIsFalse()
        {
            var jsonSample        = EmbeddedResourceManager.GetString("Assets.v2_core_error_has_data_false.json");
            var jsonRpcSerializer = new JsonRpcSerializer();

            jsonRpcSerializer.ResponseContracts["m"]     = new JsonRpcResponseContract(typeof(string));
            jsonRpcSerializer.StaticResponseBindings[1L] = "m";

            var jsonRpcData = jsonRpcSerializer.DeserializeResponseData(jsonSample);

            Assert.False(jsonRpcData.IsBatch);

            var jsonRpcItem = jsonRpcData.Item;

            Assert.True(jsonRpcItem.IsValid);

            var jsonRpcMessage = jsonRpcItem.Message;

            Assert.False(jsonRpcMessage.Success);

            var jsonRpcError = jsonRpcMessage.Error;

            Assert.False(jsonRpcError.HasData);
            Assert.Null(jsonRpcError.Data);
        }
Example #15
0
        public void CoreDeserializeRequestDataFromStreamWhenJsonStreamIsNull()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();

            Assert.Throws <ArgumentNullException>(() =>
                                                  jsonRpcSerializer.DeserializeRequestData((Stream)null));
        }
Example #16
0
        public void DeserializeRequestDataT021()
        {
            var jsont = EmbeddedResourceManager.GetString("Assets.v2_spec_02.1_req.json");
            var jrcr  = new JsonRpcContractResolver();
            var jrs   = new JsonRpcSerializer(jrcr);

            var jrmp = new Dictionary <string, Type>
            {
                ["subtrahend"] = typeof(long),
                ["minuend"]    = typeof(long)
            };

            jrcr.AddRequestContract("subtract", new JsonRpcRequestContract(jrmp));

            var jrd = jrs.DeserializeRequestData(jsont);

            Assert.IsFalse(jrd.IsBatch);

            var jrmi = jrd.Item;

            Assert.IsTrue(jrmi.IsValid);

            var jrm = jrmi.Message;

            Assert.AreEqual(4L, jrm.Id);
            Assert.AreEqual("subtract", jrm.Method);
            Assert.AreEqual(JsonRpcParametersType.ByName, jrm.ParametersType);
            Assert.AreEqual(23L, jrm.ParametersByName["subtrahend"]);
            Assert.AreEqual(42L, jrm.ParametersByName["minuend"]);
        }
Example #17
0
        public SLH(SLHClient client, SLHWebSocketServer server)
        {
            Client = client;
            Server = server;

            Server.ReceivedMessage += HandleReceivedMessage;

            Client.Network.LoginProgress += HandleLoginProgress;
            Client.Network.LoggedOut     += HandleLoggedOut;

            SessionId = new Guid().ToString();

            // Important step
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                //Converters = new[] { JSONConverter }, // Pass the shared (static) converter
                Converters = new[] { new SLHJSONConverter() },
                Error      = delegate(object sender, ErrorEventArgs args)
                {
                    // SERIALIZE ALL THE THINGS!
                    args.ErrorContext.Handled = true;
                },
            };

            // Bind this class to the JSON-RPC server
            ServiceBinder.BindService(SessionId, this);

            // Set up the JSON-RPC client serializer
            JSONRPCSerializer = new JsonRpcSerializer();
        }
Example #18
0
 public void SerializeRequestWhenParametersAreByName()
 {
     var jrs  = new JsonRpcSerializer(compatibilityLevel: JsonRpcCompatibilityLevel.Level1);
     var jrmp = new Dictionary <string, object> {
         ["p"] = 1L
     };
     var jrm = new JsonRpcRequest(default, "m", jrmp);
Example #19
0
        void DoParse(byte[] p_data)
        {
            // Utf8JsonReader不能用在异步方法内!
            Utf8JsonReader reader = new Utf8JsonReader(p_data);

            // [
            reader.Read();
            ApiName = reader.ReadAsString();
            if (string.IsNullOrEmpty(ApiName) || (Api = Silo.GetMethod(ApiName)) == null)
            {
                // 未找到对应方法
                throw new Exception($"Api方法“{ApiName}”不存在!");
            }

            var method = Api.Method.GetParameters();

            if (method.Length > 0)
            {
                // 确保和Api的参数个数、类型相同
                // 类型不同时 执行类型转换 或 直接创建派生类实例!如Row -> User, Table -> Table<User>
                int index = 0;
                Args = new object[method.Length];
                while (index < method.Length && reader.Read() && reader.TokenType != JsonTokenType.EndArray)
                {
                    // 参数支持派生类型!
                    Args[index] = JsonRpcSerializer.Deserialize(ref reader, method[index].ParameterType);
                    index++;
                }
            }
        }
        public void SerializeRequestsWhenCollectionIsNull()
        {
            var jrs = new JsonRpcSerializer();

            Assert.ThrowsException <ArgumentNullException>(() =>
                                                           jrs.SerializeRequests(null));
        }
        public async Task SerializeRequestAsyncWithStreamWhenStreamIsNull()
        {
            var jrs = new JsonRpcSerializer();
            var jrm = new JsonRpcRequest(0L, "m");

            await Assert.ThrowsExceptionAsync <ArgumentNullException>(() =>
                                                                      jrs.SerializeRequestAsync(jrm, (Stream)null, default).AsTask());
Example #22
0
        /// <summary>
        /// 解析结果,Utf8JsonReader不能用在异步方法内!
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p_data"></param>
        /// <returns></returns>
        T ParseResult <T>(byte[] p_data)
        {
            T              val    = default(T);
            RpcResult      result = new RpcResult();
            Utf8JsonReader reader = new Utf8JsonReader(p_data);

            try
            {
                // [
                reader.Read();

                // 0成功,1错误,2警告提示
                result.ResultType = (RpcResultType)reader.ReadAsInt();

                // 耗时,非调试状态为0
                reader.Read();
                result.Elapsed = reader.GetInt32().ToString();

                reader.Read();
                if (result.ResultType == RpcResultType.Value)
                {
                    // 结果
                    val = JsonRpcSerializer.Deserialize <T>(ref reader);
                }
                else
                {
                    // 错误或提示信息
                    result.Info = reader.GetString();
                }
            }
            catch
            {
                result.ResultType = RpcResultType.Error;
                result.Info       = "返回Json内容结构不正确!";
            }

#if !SERVER
            // 输出监视信息
            string content = null;
            if (Kit.TraceRpc || result.ResultType == RpcResultType.Error)
            {
                // 输出详细内容
                content = Encoding.UTF8.GetString(p_data);
            }
            Kit.Trace(TraceOutType.RpcRecv, string.Format("{0}—{1}ms", _methodName, result.Elapsed), content, _svcName);

            // ⚡ 为服务器标志
            if (result.ResultType == RpcResultType.Message)
            {
                throw new KnownException("⚡" + result.Info);
            }
#endif

            if (result.ResultType == RpcResultType.Value)
            {
                return(val);
            }
            throw new ServerException("服务器异常", result.Info);
        }
Example #23
0
        static List <string> ParseResult(byte[] p_data)
        {
            // Utf8JsonReader不能用在异步方法内!
            var reader = new Utf8JsonReader(p_data);

            reader.Read();
            return(JsonRpcSerializer.Deserialize(ref reader) as List <string>);
        }
Example #24
0
        private static JsonRpcSerializer CreateSerializerRequestParamsNone()
        {
            var serializer = new JsonRpcSerializer();

            serializer.RequestContracts["m"] = new JsonRpcRequestContract();

            return(serializer);
        }
        public void SerializeRequestWithStreamWhenStreamIsNull()
        {
            var jrs = new JsonRpcSerializer();
            var jrm = new JsonRpcRequest(0L, "m");

            Assert.ThrowsException <ArgumentNullException>(() =>
                                                           jrs.SerializeRequest(jrm, (Stream)null));
        }
Example #26
0
        public void CoreSerializeRequestToStreamWhenStreamIsNull()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();
            var jsonRpcMessage    = new JsonRpcRequest("m", 0L);

            Assert.Throws <ArgumentNullException>(() =>
                                                  jsonRpcSerializer.SerializeRequest(jsonRpcMessage, null));
        }
Example #27
0
        public async void CoreDeserializeResponseDataAsyncFromStreamWhenJsonStreamIsEmpty()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();

            var exception = await Assert.ThrowsAsync <JsonRpcException>(() =>
                                                                        jsonRpcSerializer.DeserializeResponseDataAsync(Stream.Null));

            Assert.Equal(JsonRpcErrorCodes.InvalidJson, exception.ErrorCode);
        }
Example #28
0
        public void CoreSerializeResponsesWhenCollectionContainsNull()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();

            var exception = Assert.Throws <JsonRpcException>(() =>
                                                             jsonRpcSerializer.SerializeResponses(new JsonRpcResponse[] { null }));

            Assert.Equal(JsonRpcErrorCodes.InvalidMessage, exception.ErrorCode);
        }
Example #29
0
        public void CoreSerializeRequestsWhenCollectionIsEmpty()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();

            var exception = Assert.Throws <JsonRpcException>(() =>
                                                             jsonRpcSerializer.SerializeRequests(new JsonRpcRequest[] { }));

            Assert.Equal(JsonRpcErrorCodes.InvalidMessage, exception.ErrorCode);
        }
Example #30
0
        public void CoreDeserializeResponseDataWhenJsonStringIsEmpty()
        {
            var jsonRpcSerializer = new JsonRpcSerializer();

            var exception = Assert.Throws <JsonRpcException>(() =>
                                                             jsonRpcSerializer.DeserializeResponseData(string.Empty));

            Assert.Equal(JsonRpcErrorCodes.InvalidJson, exception.ErrorCode);
        }
Example #31
0
        private static void Main(string[] args)
        {
            JsonRpcSerializer serializer = new JsonRpcSerializer();

            AsyncHttpClient client = new AsyncHttpClient(serializer);
            client.BaseUri = new Uri("http://Suffix:8080/jsonrpc");
            AudioLibraryClient libraryClient = new AudioLibraryClient(client, serializer);
            PlayerClient playerClient = new PlayerClient(client, serializer);
            //XbmcServerClient serverClient = new XbmcServerClient(client);
            PlaylistClient playlist = new PlaylistClient(client, serializer);
            FilesClient files = new FilesClient(client, serializer);

            XbmcPlayer player = new XbmcPlayer { Id = 0 };
            //playerClient.PlayPause(ResultAction, player);
            PlayerProperties props = playerClient.GetProperties(player).Result;

            IEnumerable<Playlist> playlists = playlist.GetPlaylists().Result;

            IMediaItemList<MediaDetailsBase> items = playlist.GetItems(playlists.First()).Result;

            var artists = libraryClient.GetArtists(null, null, ArtistFields.All, 0, 50, SortMethods.Album, Orders.Ascending).Result;

            var fs = files.GetMusicPlaylists().Result;

            //player.GetItem(ResultAction);
            //player.GetProperties(Result);
            //player.Seek(ResultAction, 10);

            //library.GetAlbums(ResultAction, 214, null, null, 2, null);
            //library.GetArtists(ResultAction);
            //library.GetSongs(ResultAction, null, null, null);
            //library.GetSong(ResultAction, 6695, null);
            //library.GetAlbum(ResultAction, 470, null);
            //library.GetArtist(ResultAction, 215, null);

            //player.OpenAlbum(ResultAction, 469);

            //server.Introspect(ResultAction);
            //server.ToggleMute(ResultAction);
            //server.Ping(ResultAction);
            //server.GetVersion(ResultAction);

            //playlist.Remove(ResultAction, new Playlist { Id = 0 }, 1);
            //playlist.Add(ResultAction, new Playlist { Id = 0 }, new Album { Id = 470 });
            //playlist.GetItems(ResultAction, new Playlist { Id = 0 });
            //playlist.GetPlaylists(ResultAction);

            Console.ReadLine();
        }
 public AudioLibraryClient(AsyncHttpClient client, JsonRpcSerializer serializer)
 {
     _client = client;
     _serializer = serializer;
 }
 public PlayerClient(AsyncHttpClient client, JsonRpcSerializer jsonRpcSerializer)
 {
     _client = client;
     _jsonRpcSerializer = jsonRpcSerializer;
 }
 public PlaylistClient(AsyncHttpClient client, JsonRpcSerializer serializer)
 {
     _client = client;
     _serializer = serializer;
 }
 public FilesClient(AsyncHttpClient client, JsonRpcSerializer serializer)
 {
     _client = client;
     _serializer = serializer;
 }