private static void InitialSetup() { //betfair connection var provider = new AppKeyAndSessionProvider(ConfigurationManager.AppSettings["ssoHost"], ConfigurationManager.AppSettings["appKey"], ConfigurationManager.AppSettings["userName"], ConfigurationManager.AppSettings["password"]); var session = provider.GetOrCreateNewSession(); Client = new JsonRpcClient(_url, session.AppKey, session.Session); //Betfair Hub var url = string.Format(ConfigurationManager.AppSettings["ratingsFile"], DateTime.Today); using (var client = new WebClient()) { var ratings = client.DownloadString(url); System.IO.File.WriteAllText($"ratings-{DateTime.Now:yyyyMMddHHmm}.json", ratings); Ratings = JsonConvert.DeserializeObject <Ratings>(ratings); } LoadMarkets(); var startTimeSpan = TimeSpan.FromMinutes(2); var periodTimeSpan = TimeSpan.FromMinutes(2); var timer = new System.Threading.Timer((e) => { LoadMarkets(); }, null, startTimeSpan, periodTimeSpan); }
private void GetSecurityToken() { // we expect this file to be open by now // because we get here from auth exception String coltFileName = GetCOLTFile(); if (coltFileName != null) { try { JsonRpcClient client = new JsonRpcClient(coltFileName); // knock client.Invoke("requestShortCode", new Object[] { "FlashDevelop" /*LocaleHelper.GetString("Info.Description").TrimEnd(new Char[] { '.' })*/ }); // if still here, user needs to enter the code Forms.FirstTimeDialog dialog = new Forms.FirstTimeDialog(settingObject.InterceptBuilds, settingObject.AutoRun); dialog.ShowDialog(); // regardless of the code, set boolean options settingObject.AutoRun = dialog.AutoRun; settingObject.InterceptBuilds = dialog.InterceptBuilds; if ((dialog.ShortCode != null) && (dialog.ShortCode.Length == 4)) { // short code looks right - request security token settingObject.SecurityToken = client.Invoke("obtainAuthToken", new Object[] { dialog.ShortCode }).ToString(); } } catch (Exception details) { HandleAuthenticationExceptions(details); } } }
/// <summary> /// Makes production build and optionally runs its output /// </summary> private void ProductionBuild(Boolean run) { // make sure the COLT project is open String path = FindAndOpen(false); if (path != null) { try { JsonRpcClient client = new JsonRpcClient(path); client.PingOrRunCOLT(settingObject.Executable); // leverage FD launch mechanism if (run) { client.InvokeAsync("runProductionCompilation", RunAfterProductionBuild, new Object[] { settingObject.SecurityToken, /*run*/ false }); } else { client.InvokeAsync("runProductionCompilation", HandleAuthenticationExceptions, new Object[] { settingObject.SecurityToken, /*run*/ false }); } } catch (Exception details) { HandleAuthenticationExceptions(details); } } }
public async Task <Error> SendNotificationUri(string uri) { Parameters parameters = new Parameters(); parameters.plugin = "pushNotification"; parameters.platform = "windows"; parameters.query = uri; if (config.IdPush != null) { parameters.id = config.IdPush; } var jsonrpc = new JsonRpcClient(parameters); if (await jsonrpc.SendRequest("Iq")) { // Récupère la liste de tous les eqLogics var reponse = jsonrpc.GetRequestResponseDeserialized <Response <string> >(); if (reponse != null) { config.IdPush = reponse.result; } } return(jsonrpc.Error); }
public JsonRpcException(JsonRpcClient jsonRpcClient, JsonRpcError error) : base($"{jsonRpcClient.Uri} returned Error {error.Code}: {error.Message}") { this.Uri = jsonRpcClient.Uri; this.Code = error.Code; this.ErrorMessage = error.Message; }
public static async Task <LocalTestNet> Setup() { var localTestNet = new LocalTestNet(); try { // Bootstrap local testnode // TODO: check cmd args for account options localTestNet.TestNodeServer = new TestNodeServer(); localTestNet.TestNodeServer.RpcServer.Start(); // Setup rpcclient // TODO: check cmd args for gas options localTestNet.RpcClient = JsonRpcClient.Create( localTestNet.TestNodeServer.RpcServer.ServerAddress, ArbitraryDefaults.DEFAULT_GAS_LIMIT, ArbitraryDefaults.DEFAULT_GAS_PRICE); // Enable Meadow debug RPC features. await localTestNet.RpcClient.SetTracingEnabled(true); // Configure Meadow rpc error formatter. localTestNet.RpcClient.ErrorFormatter = GetExecutionTraceException; // Get accounts. localTestNet.Accounts = await localTestNet.RpcClient.Accounts(); } catch { localTestNet.Dispose(); throw; } return(localTestNet); }
private static void InvokeTest(JsonRpcClient client, int testCount) { for (int i = 0; i < testCount; i++) { client.InvokeAsync("SpeedNoArgs").Wait(); } }
public void TestSettingJsonRpcExceptionWithContext() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "error4"; string input = "Hello"; JsonResponse <string[]> result = null; var myObs = rpc.Invoke <string[]>(method, input, Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); Assert.IsTrue(result.Result == null); var res = result.Error; Assert.IsTrue(res is AustinHarris.JsonRpc.JsonRpcException); if (res is JsonRpcException) { Assert.IsTrue(res.message == "This exception was thrown using: JsonRpcContext.Current().SetException()"); } }
public void TestPreProcessingException() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "RequiresCredentials"; string input = "BadPassword"; JsonResponse <string[]> result = null; var myObs = rpc.Invoke <string[]>(method, input, Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); Assert.IsTrue(result.Result == null); var res = result.Error; Assert.IsTrue(res is AustinHarris.JsonRpc.JsonRpcException); if (res is JsonRpcException) { Assert.IsTrue(res.message == "This exception was thrown using: JsonRpcTest.Global.PreProcess, Not Authenticated"); } }
public void TestMetaData() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "?"; JsonResponse <Newtonsoft.Json.Linq.JObject> result = null; var myObs = rpc.Invoke <Newtonsoft.Json.Linq.JObject>(method, null, Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); var res = result.Result; }
public void TestEcho() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "internal.echo"; string input = "Echo this sucka"; JsonResponse <string> result = null; var myObs = rpc.Invoke <string>(method, input, Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); var res = result.Result; Assert.IsTrue(res == input.ToString()); }
static void Main(string[] args) { Console.WriteLine("**** Simple PerfTest ****\n"); int threadCount = Debugger.IsAttached ? 1 : 8; const int testCount = 1_000_000; const int port = 54343; // Make progress updates smoother Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; using (var server = new MyServer(port)) { server.Bind(typeof(Target)); // Bind to functions on static class Console.WriteLine($"Making {threadCount} client connections"); var clients = new JsonRpcClient[threadCount]; for (int i = 0; i < threadCount; i++) { clients[i] = MyClient.ConnectAsync(port).Result; } Console.WriteLine($"Warmup"); RunLatencyTest(true).Wait(); RunNotifyTest(threadCount, threadCount * 10000, clients, true); RunInvokeTest(threadCount, threadCount * 1000, clients, true); Console.WriteLine($"Running the tests...\n"); RunLatencyTest().Wait(); RunNotifyTest(threadCount, testCount, clients); RunInvokeTest(threadCount, testCount / 10, clients); } }
static void Main(string[] args) { ThreadPool.SetMinThreads(65535, 65535); var remoteUrl = "http://127.0.0.1:8090/"; if (args.Length != 0 && (args[0].StartsWith("http") || args[0].StartsWith("ws"))) { remoteUrl = args[0]; } var client = new JsonRpcClient(); IJsonRpcClientEngine clientEngine = remoteUrl.StartsWith("http")? new JsonRpcHttpClientEngine(remoteUrl): new JsonRpcWebSocketClientEngine(remoteUrl); bool ws = clientEngine is JsonRpcWebSocketClientEngine; client.UseEngine(clientEngine); var testCount = 3; if (args.Contains("-benchmark")) { testCount = 100; } var statisticsList = new List <int>(); for (var i = 0; i < testCount; i++) { statisticsList.Add(Benchmark(client, TestData, ws)); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine($"Best: {statisticsList.Max()} rpc/sec, \t Average: {(int)statisticsList.Average()} rpc/sec, \t Worst: {statisticsList.Min()} rpc/sec"); Console.ReadLine(); }
static void Main(string[] args) { CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-us"); Console.InputEncoding = Encoding.UTF8; Console.OutputEncoding = Encoding.UTF8; CommandLineArguments.ParseFrom(args); if (CommandLineArguments.WaitForDebugger) { while (!Debugger.IsAttached) { Thread.Sleep(1000); } Debugger.Break(); } var host = BuildServiceHost(); var serverHandler = new StreamRpcServerHandler(host); var clientHandler = new StreamRpcClientHandler(); var client = new JsonRpcClient(clientHandler); var serviceContext = new SandboxHost(client, CommandLineArguments.SandboxPath); serverHandler.DefaultFeatures.Set(serviceContext); // Messages come from Console ByLineTextMessageReader reader; ByLineTextMessageWriter writer; if (!string.IsNullOrEmpty(CommandLineArguments.RxHandle)) { var pipeClient = new AnonymousPipeClientStream(PipeDirection.In, CommandLineArguments.RxHandle); reader = new ByLineTextMessageReader(pipeClient); } else { reader = new ByLineTextMessageReader(Console.In); } if (!string.IsNullOrEmpty(CommandLineArguments.TxHandle)) { var pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, CommandLineArguments.TxHandle); writer = new ByLineTextMessageWriter(pipeClient); } else { writer = new ByLineTextMessageWriter(Console.Out); } try { using (reader) using (writer) using (serverHandler.Attach(reader, writer)) using (clientHandler.Attach(reader, writer)) { // Started up. serviceContext.HostingClient.NotifyStarted(); // Wait for exit serviceContext.Disposal.Wait(); } } catch (ObjectDisposedException) { } }
/// <summary> /// Closes the connection and doesn't yield. /// </summary> /// <param name="stopCoroutines">If false, coroutines would not stop (used for stopping the game in the Unity editor)</param> public void CloseImmidiately(bool stopCoroutines = true) { if (Authorized && stopCoroutines) { if (_authorizationContext != null) { EndAuthorizationContext(); } if (_processBulkRequestCoroutine != null) { CoroutineManager.StopCoroutine(_processBulkRequestCoroutine); } if (_trackContextDataCoroutine != null) { CoroutineManager.StopCoroutine(_trackContextDataCoroutine); } // Unsubscribe from events JsonRpcClient.OnLostConnection -= OnLostConnection; JsonRpcClient.OnReconnected -= OnReconnected; } JsonRpcClient.CloseImmidiately(); }
private static void NotifyTest(JsonRpcClient client, int testCount) { for (int i = 0; i < testCount; i++) { client.Notify("SpeedNoArgs"); } }
public async Task ExecuteCommand(Command cmd, Parameters parameters = null) { if (config.IsDemoEnabled) { return; } cmd.Updating = true; if (parameters == null) { parameters = new Parameters(); parameters.id = cmd.id; parameters.name = cmd.name; } var jsonrpc = new JsonRpcClient(parameters); if (await jsonrpc.SendRequest("cmd::execCmd")) { var response = jsonrpc.GetRequestResponseDeserialized <Response <CommandResult> >(); cmd.value = response.result.value; } else { cmd.value = "N/A"; } cmd.Updating = false; }
public JsonRpcIntegrationTestBase(ITestOutputHelper output) { this.output = output; var configs = new JsonRpcServerConfigurations() { BindingPort = port, //Interlocked.Increment(ref port), TransportProtocol = JsonRpcServerConfigurations.TransportMode.Bson }; server = new JsonRpcServer<TestActionHandler>(configs); client = JsonRpcClient<TestActionHandler>.CreateClient("localhost", server.Configurations.BindingPort, JsonRpcServerConfigurations.TransportMode.Bson); client.Info.Username = "******"; client.OnAuthenticationRequest += (sender, e) => { e.Data = AUTH_TEXT; }; server.OnAuthenticationVerification += (sender, e) => { e.Authenticated = true; }; server.OnStop += (sender, e) => { wait.Set(); }; }
static void Main(string[] args) { var debugMode = args.Any(a => a.Equals("--debug", StringComparison.OrdinalIgnoreCase)); #if WAIT_FOR_DEBUGGER while (!Debugger.IsAttached) { Thread.Sleep(1000); } Debugger.Break(); #endif StreamWriter logWriter = null; if (debugMode) { logWriter = File.CreateText("messages-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log"); logWriter.AutoFlush = true; } using (logWriter) using (var cin = Console.OpenStandardInput()) using (var bcin = new BufferedStream(cin)) using (var cout = Console.OpenStandardOutput()) using (var reader = new PartwiseStreamMessageReader(bcin)) using (var writer = new PartwiseStreamMessageWriter(cout)) { var contractResolver = new JsonRpcContractResolver { NamingStrategy = new CamelCaseJsonRpcNamingStrategy(), ParameterValueConverter = new LanguageServiceParameterValueConverter(), }; var clientHandler = new StreamRpcClientHandler(); var client = new JsonRpcClient(clientHandler); if (debugMode) { // We want to capture log all the LSP server-to-client calls as well clientHandler.MessageSending += (_, e) => { lock (logWriter) logWriter.WriteLine("{0} <C{1}", Utility.GetTimeStamp(), e.Message); }; clientHandler.MessageReceiving += (_, e) => { lock (logWriter) logWriter.WriteLine("{0} >C{1}", Utility.GetTimeStamp(), e.Message); }; } // Configure & build service host var session = new LanguageServerSession(client, contractResolver); var host = BuildServiceHost(logWriter, contractResolver, debugMode); var serverHandler = new StreamRpcServerHandler(host, StreamRpcServerHandlerOptions.ConsistentResponseSequence | StreamRpcServerHandlerOptions.SupportsRequestCancellation); serverHandler.DefaultFeatures.Set(session); // If we want server to stop, just stop the "source" using (serverHandler.Attach(reader, writer)) using (clientHandler.Attach(reader, writer)) { // Wait for the "stop" request. session.CancellationToken.WaitHandle.WaitOne(); } logWriter?.WriteLine("Exited"); } }
private async Task Example3(CancellationToken cancelToken = default) { using (var svc = new JsonRpcClient(SampleServerUri).AsServiceContract <ISampleService2>()) { try { var cts = CancellationTokenSource.CreateLinkedTokenSource(cancelToken); var res1 = await svc.Method3(cts.Token).CancelAfter(5000, cts).ConfigureAwait(false); } catch (TimeoutException) { Console.WriteLine("Operation timed out..."); } catch (JsonRpcRequestException x) { Console.WriteLine($"StatusCode = {x.StatusCode}, details = {x.ToString()}"); } catch (Exception x) { Console.WriteLine(x.Message); } await svc.Method4().ConfigureAwait(false); await svc.Method5("Test123").ConfigureAwait(false); } }
private async Task Example1() { var parameters = new Dictionary <string, object> { ["apiKey"] = "00000000-0000-0000-0000-000000000000" }; using (var client = new JsonRpcClient(RandomServerUri)) { var result = await client.InvokeAsync <KeyUsage>("getUsage", parameters).ConfigureAwait(false); Console.WriteLine($"getUsage, BitsLeft = {result.BitsLeft}"); } using (var svc = new JsonRpcClient(RandomServerUri).AsServiceContract <IRandomApi>()) { var res = await svc.GetUsage("00000000-0000-0000-0000-000000000000").ConfigureAwait(false); Console.WriteLine($"GetUsage, BitsLeft = {res.BitsLeft}"); var res2 = await svc.GenerateIntegers("00000000-0000-0000-0000-000000000000", 3, -100, 200).ConfigureAwait(false); Console.WriteLine($"Received random numbers: {String.Join(", ",res2?.Random.Data?.Take(10) ?? new int[0])}"); } }
public Object JsonCommand(string cmd, Object parameter) { if (!_configured) { return(null); } var client = new JsonRpcClient { Url = GetJsonPath(), Timeout = GetTimeout() }; var creds = GetCredentials(); if (creds != null) { client.Credentials = creds; } object retval = null; var logparam = ""; if (parameter != null) { logparam = parameter.GetType().ToString() == "System.String[]" ? String.Join(",", (string[])parameter) : parameter.ToString(); } try { lock (Locker) { retval = JsonConvert.Import(client.Invoke(cmd, parameter).ToString()); } if (cmd != "JSONRPC.Ping" && cmd != "VideoPlayer.GetTime" && cmd != "System.GetInfoLabels" && cmd != "AudioPlayer.GetTime") { Log("JSONCMD : " + cmd + ((parameter == null) ? "" : " - " + logparam)); } else { Trace("JSONCMD : " + cmd + ((parameter == null) ? "" : " - " + logparam)); } } catch (JsonException e) { if (cmd != "JSONRPC.Ping") { Log("JSONCMD : " + cmd + ((parameter == null) ? "" : " : " + logparam) + " - " + e.Message); } else { Trace("JSONCMD : " + cmd + ((parameter == null) ? "" : " : " + logparam) + " - " + e.Message); } } finally { client.Dispose(); } if (retval != null) { Trace(retval.ToString()); } return(retval); }
public JsonRpcClient GetConnection() { if (RpcClient == null) { RpcClient = new JsonRpcClient(Url, GetClient()); } return(RpcClient); }
public AsmoneyAPI(string username, string apiname, string apipassword) { m_username = username; m_apiname = apiname; m_password = apipassword; m_client = new JsonRpcClient(); m_client.Url = "https://www.asmoney.com/api.ashx"; }
internal XbmcPlayer(JsonRpcClient client) : base(client) { //this.id = -1; this.audio = new XbmcAudioPlayer(client); this.video = new XbmcVideoPlayer(client); this.pictures = new XbmcPicturePlayer(client); }
public RpcServerProxy(Uri targetHost, int?proxyServerPort = null, IPAddress address = null) { _proxyClient = JsonRpcClient.Create(targetHost, ArbitraryDefaults.DEFAULT_GAS_LIMIT, ArbitraryDefaults.DEFAULT_GAS_PRICE); _httpServer = new JsonRpcHttpServer(_proxyClient, ConfigureWebHost, proxyServerPort, address); //var undefinedRpcMethods = this.GetUndefinedRpcMethods(); //Console.WriteLine("Warning: following RPC methods are not defined: \n" + string.Join(", ", undefinedRpcMethods.Select(r => r.Value()))); }
static void Main(string[] args) { ThreadPool.SetMinThreads(65535, 65535); var server = new JsonRpcServer(); var client = new JsonRpcClient(); if (args.Contains("-debug")) { Logger.DebugMode = true; Logger.UseDefaultWriter(); } if (args.Contains("-benchmark")) { var engine = new JsonRpcInProcessEngine(); server.UseEngine(engine); client.UseEngine(engine); server.Start(); var statisticsList = new List <int>(); for (var i = 0; i < 20; i++) { statisticsList.Add(Benchmark(client, TestData)); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine($"Best: {statisticsList.Max()} rpc/sec, \t Average: {(int)statisticsList.Average()} rpc/sec, \t Worst: {statisticsList.Min()} rpc/sec"); } else { IJsonRpcServerEngine serverEngine; if (args.Contains("-websocket")) { serverEngine = new JsonRpcWebSocketServerEngine("http://*:8090/"); server.UseEngine(serverEngine); } else if (args.Contains("-websocket-kestrel")) { serverEngine = new JsonRpcKestrelWebSocketServerEngine(IPAddress.Any, 8090); server.UseEngine(serverEngine); } else if (args.Contains("-http-kestrel")) { serverEngine = new JsonRpcKestrelHttpServerEngine(IPAddress.Any, 8090); server.UseEngine(serverEngine); } else { serverEngine = new JsonRpcHttpServerEngine("http://*:8090/"); server.UseEngine(serverEngine); } server.Start(); Console.WriteLine($"JsonRpc Server Started with engine: {serverEngine.Name}."); } Console.ReadLine(); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); _jsonClient = new Model.JsonRpcClient(_serverHost); InitControlAction(); }
public static Task Process(JsonRpcClient client, string requestStr) { return(Task.Factory.StartNew(() => { var task = client.BenchmarkAsync("test", requestStr); task.Wait(); task.Dispose(); })); }
public RpcApp() { Server = new MockServerApp(); Server.RpcServer.WebHost.Start(); var port = Server.RpcServer.ServerPort; HttpClient = JsonRpcClient.Create(new Uri($"http://{IPAddress.Loopback}:{port}"), ArbitraryDefaults.DEFAULT_GAS_LIMIT, ArbitraryDefaults.DEFAULT_GAS_PRICE); WebSocketClient = JsonRpcClient.Create(new Uri($"ws://{IPAddress.Loopback}:{port}"), ArbitraryDefaults.DEFAULT_GAS_LIMIT, ArbitraryDefaults.DEFAULT_GAS_PRICE); }
public static async Task RunClientAsync(Stream clientStream) { await Task.Yield(); // We want this task to run on another thread. var clientHandler = new StreamRpcClientHandler(); using (var reader = new ByLineTextMessageReader(clientStream)) using (var writer = new ByLineTextMessageWriter(clientStream)) using (clientHandler.Attach(reader, writer)) { var client = new JsonRpcClient(clientHandler); var builder = new JsonRpcProxyBuilder { ContractResolver = myContractResolver }; var proxy = builder.CreateProxy <ILibraryService>(client); ClientWriteLine("Add books…"); await proxy.PutBookAsync(new Book("Somewhere Within the Shadows", "Juan Díaz Canales & Juanjo Guarnido", new DateTime(2004, 1, 1), "1596878177")); await proxy.PutBookAsync(new Book("Arctic Nation", "Juan Díaz Canales & Juanjo Guarnido", new DateTime(2004, 1, 1), "0743479351")); ClientWriteLine("Available books:"); foreach (var isbn in await proxy.EnumBooksIsbn()) { var book = await proxy.GetBookAsync(isbn); ClientWriteLine(book); } ClientWriteLine("Attempt to query for an inexistent ISBN…"); try { await proxy.GetBookAsync("test", true); } catch (JsonRpcRemoteException ex) { ClientWriteLine(ex); } ClientWriteLine("Attempt to pass some invalid argument…"); try { await proxy.PutBookAsync(null); } catch (JsonRpcRemoteException ex) { ClientWriteLine(ex); } ClientWriteLine("Will shut down server in 5 seconds…"); await Task.Delay(5000); proxy.Terminate(); } }
public async Task InvokeEchoShouldBeOkAsync() { var settings = new Settings(); var client = new JsonRpcClient(_client, settings); var echoResult = await client.InvokeFuncAsync <string>(new Uri("/projects/jayrock/demo.ashx", UriKind.Relative), "echo", new[] { "hello" }); Assert.Equal("hello", echoResult); }
/// <summary> /// The default constructor, creates a test chain for tests to share. /// </summary> public TestChainFixture() { // Create a test node on this port. Server = new Meadow.TestNode.TestNodeServer(); Server.RpcServer.Start(); int port = Server.RpcServer.ServerPort; // Create our client and grab our account list. Client = JsonRpcClient.Create(new Uri($"http://{IPAddress.Loopback}:{port}"), ArbitraryDefaults.DEFAULT_GAS_LIMIT, ArbitraryDefaults.DEFAULT_GAS_PRICE); }
protected XbmcMediaLibrary(string libraryName, JsonRpcClient client) : base(client) { if (string.IsNullOrEmpty(libraryName)) { throw new ArgumentException(); } this.libraryName = libraryName; }
public static async Task<Error> PingJeedom() { var jsonrpc = new JsonRpcClient(); if (await jsonrpc.SendRequest("ping")) { var response = jsonrpc.GetRequestResponseDeserialized<ResponseString>(); if (response.result == "pong") return null; } return jsonrpc.Error; }
public XbmcClient(string baseUrl, string username, string password, bool executeCallbackOnUIThread = true) { client = new JsonRpcClient(this.BuildUrl(baseUrl), executeCallbackOnUIThread); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { this.credentials = new NetworkCredential(username, password); } this.Video = new VideoLibrary(client, GetRequestId, this.credentials); this.Vfs = new Vfs(new Uri(baseUrl), this.credentials, executeCallbackOnUIThread); }
public XbmcJsonRpcConnection(Uri uri, string username, string password) { this.client = new JsonRpcClient(uri, username, password); this.client.Log += onLog; this.client.LogError += onLogError; this.jsonRpc = new XbmcJsonRpc(this.client); this.player = new XbmcPlayer(this.client); this.system = new XbmcSystem(this.client); this.xbmc = new XbmcGeneral(this.client); this.files = new XbmcFiles(this.client); this.playlist = new XbmcPlaylist(this.client); this.library = new XbmcLibrary(this.client); }
protected XbmcMediaPlayer(string playerName, string infoLabelName, JsonRpcClient client, int id) : base(client) { if (string.IsNullOrEmpty(playerName)) { throw new ArgumentException(); } if (string.IsNullOrEmpty(infoLabelName)) { infoLabelName = playerName; } this.playerName = playerName; this.infoLabelName = infoLabelName; this.id = (id == -1) ? (id = 1) : id; }
internal static XbmcArtist FromJson(JObject obj, JsonRpcClient logger) { if (obj == null) { return null; } try { return new XbmcArtist(JsonRpcClient.GetField<int>(obj, "artistid"), JsonRpcClient.GetField<string>(obj, "artist"), JsonRpcClient.GetField<string>(obj, "thumbnail"), JsonRpcClient.GetField<string>(obj, "fanart")); } catch (Exception ex) { if (logger != null) logger.LogErrorMessage("EXCEPTION in XbmcArtist.FromJson()!!!", ex); return null; } }
private static void Main() { var client = new JsonRpcClient("http://*****:*****@example.com", PhoneNumber = "555-1212", }); System.Console.WriteLine(id); System.Console.ReadKey(); }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); JsonRpcClient client = new JsonRpcClient(new Uri("http://localhost:49718/json.rpc")); var request = client.Invoke<object>("internal.echo", "hi", Scheduler.ThreadPool); request.Subscribe( response => { this.response = response; }, error => { ex = error; }, () => { done = true; } ); }
internal static new XbmcMovie FromJson(JObject obj, JsonRpcClient logger) { if (obj == null) { return null; } try { // TODO: Remove unsupported label (e.g. 'movieid') return new XbmcMovie(JsonRpcClient.GetField<int>(obj, "movieid"), JsonRpcClient.GetField<string>(obj, "thumbnail"), JsonRpcClient.GetField<string>(obj, "fanart"), JsonRpcClient.GetField<string>(obj, "file"), JsonRpcClient.GetField<string>(obj, "title"), JsonRpcClient.GetField<string>(obj, "genre", string.Empty), JsonRpcClient.GetField<int>(obj, "year"), JsonRpcClient.GetField<double>(obj, "rating"), JsonRpcClient.GetField<string>(obj, "director", string.Empty), JsonRpcClient.GetField<string>(obj, "trailer", string.Empty), JsonRpcClient.GetField<string>(obj, "tagline", string.Empty), JsonRpcClient.GetField<string>(obj, "plot", string.Empty), JsonRpcClient.GetField<string>(obj, "plotoutline", string.Empty), JsonRpcClient.GetField<string>(obj, "originaltitle", string.Empty), JsonRpcClient.GetField<string>(obj, "lastplayed", string.Empty), JsonRpcClient.GetField<int>(obj, "duration"), JsonRpcClient.GetField<int>(obj, "playcount"), JsonRpcClient.GetField<string>(obj, "writer", string.Empty), JsonRpcClient.GetField<string>(obj, "studio", string.Empty), JsonRpcClient.GetField<string>(obj, "mpaa", string.Empty)); } catch (Exception ex) { if (logger != null) logger.LogErrorMessage("EXCEPTION in XbmcMovie.FromJson()!!!", ex); return null; } }
public void TestMultipleParameters() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "testMultipleParameters"; var anon = new CustomString { str = "Hello" }; var input = new object[] {"one", 2, 3.3f, anon}; JsonResponse<object[]> result = null; var myObs = rpc.Invoke<object[]>(method, input, Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); Assert.IsTrue(result.Result != null); var res = result.Result; Assert.IsTrue(res.Length == 4); Assert.IsTrue((string)res[0] == (string)input[0]); Assert.IsTrue((long)res[1] == (long)(int)input[1]); Assert.IsTrue((double)res[2] == Double.Parse(input[2].ToString())); Assert.IsTrue(Newtonsoft.Json.JsonConvert.DeserializeObject<CustomString>(res[3].ToString()).str == anon.str); }
public void TestCustomString() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "testCustomString"; var input = new { str = "Hello" }; JsonResponse<string[]> result = null; var myObs = rpc.Invoke<string[]>(method, input, Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); var res = result.Result; Assert.IsTrue(res is IList<string>); var il = res as IList<string>; Assert.IsTrue(il[0] == "one"); Assert.IsTrue(il[1] == "two"); Assert.IsTrue(il[2] == "three"); Assert.IsTrue(il[3] == input.str); Assert.IsTrue(il.Count == 4); }
public void TestPreProcessingException() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "RequiresCredentials"; string input = "BadPassword"; JsonResponse<string[]> result = null; var myObs = rpc.Invoke<string[]>(method, input, Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); Assert.IsTrue(result.Result == null); var res = result.Error; Assert.IsTrue(res is AustinHarris.JsonRpc.JsonRpcException); if (res is JsonRpcException) { Assert.IsTrue(res.message == "This exception was thrown using: JsonRpcTest.Global.PreProcess, Not Authenticated"); } }
public void TestSettingJsonRpcExceptionWithContext() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "error4"; string input = "Hello"; JsonResponse<string[]> result = null; var myObs = rpc.Invoke<string[]>(method, input, Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); Assert.IsTrue(result.Result == null); var res = result.Error; Assert.IsTrue(res is AustinHarris.JsonRpc.JsonRpcException); if (res is JsonRpcException) { Assert.IsTrue(res.message == "This exception was thrown using: JsonRpcContext.Current().SetException()"); } }
public void TestEcho() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "internal.echo"; string input = "Echo this sucka"; JsonResponse<string> result = null; var myObs = rpc.Invoke<string>(method, input , Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); var res = result.Result; Assert.IsTrue(res == input.ToString()); }
public void TestMetaData() { AutoResetEvent are = new AutoResetEvent(false); var rpc = new JsonRpcClient(remoteUri); string method = "?"; JsonResponse<Newtonsoft.Json.Linq.JObject> result = null; var myObs = rpc.Invoke<Newtonsoft.Json.Linq.JObject>(method, null, Scheduler.TaskPool); myObs.Subscribe( onNext: _ => { result = _; are.Set(); }, onError: _ => { are.Set(); }, onCompleted: () => { are.Set(); } ); are.WaitOne(); Assert.IsTrue(result != null); var res = result.Result; }
internal static new XbmcTvShow FromJson(JObject obj, JsonRpcClient logger) { if (obj == null) { return null; } try { return new XbmcTvShow(JsonRpcClient.GetField<int>(obj, "tvshowid"), JsonRpcClient.GetField<string>(obj, "thumbnail"), JsonRpcClient.GetField<string>(obj, "fanart"), JsonRpcClient.GetField<string>(obj, "title"), JsonRpcClient.GetField<string>(obj, "genre", string.Empty), JsonRpcClient.GetField<int>(obj, "year"), JsonRpcClient.GetField<double>(obj, "rating"), JsonRpcClient.GetField<string>(obj, "plot", string.Empty), JsonRpcClient.GetField<int>(obj, "episode"), JsonRpcClient.GetField<int>(obj, "playcount"), JsonRpcClient.GetField<string>(obj, "studio", string.Empty), JsonRpcClient.GetField<string>(obj, "mpaa", string.Empty), JsonRpcClient.GetField<string>(obj, "premiered", string.Empty)); } catch (Exception ex) { if (logger != null) logger.LogErrorMessage("EXCEPTION in XbmcTvShow.FromJson()!!!", ex); return null; } }
internal static XbmcAlbum FromJson(JObject obj, JsonRpcClient logger) { if (obj == null) { return null; } try { return new XbmcAlbum(JsonRpcClient.GetField<int>(obj, "albumid"), JsonRpcClient.GetField<string>(obj, "thumbnail"), JsonRpcClient.GetField<string>(obj, "fanart"), JsonRpcClient.GetField<string>(obj, "album_title"), JsonRpcClient.GetField<string>(obj, "album_artist"), JsonRpcClient.GetField<int>(obj, "year"), JsonRpcClient.GetField<int>(obj, "album_rating"), JsonRpcClient.GetField<string>(obj, "album_genre", string.Empty), JsonRpcClient.GetField<string>(obj, "album_mood", string.Empty), JsonRpcClient.GetField<string>(obj, "album_theme", string.Empty), JsonRpcClient.GetField<string>(obj, "album_style", string.Empty), JsonRpcClient.GetField<string>(obj, "album_type", string.Empty), JsonRpcClient.GetField<string>(obj, "album_label", string.Empty), JsonRpcClient.GetField<string>(obj, "album_description", string.Empty)); } catch (Exception ex) { if (logger != null) logger.LogErrorMessage("EXCEPTION in XbmcAlbum.FromJson()!!!", ex); return null; } }
public async Task RunScene(Scene scene) { var parameters = new Parameters(); parameters.id = scene.id; parameters.state = "run"; var jsonrpc = new JsonRpcClient(parameters); if (await jsonrpc.SendRequest("scenario::changeState")) { await UpdateScene(scene); } }
internal static XbmcSong FromJson(JObject obj, JsonRpcClient logger) { if (obj == null) { return null; } try { return new XbmcSong(JsonRpcClient.GetField<int>(obj, "songid"), JsonRpcClient.GetField<string>(obj, "thumbnail"), JsonRpcClient.GetField<string>(obj, "fanart"), JsonRpcClient.GetField<string>(obj, "file"), JsonRpcClient.GetField<string>(obj, "title"), JsonRpcClient.GetField<string>(obj, "artist"), JsonRpcClient.GetField<string>(obj, "genre", string.Empty), JsonRpcClient.GetField<int>(obj, "year"), JsonRpcClient.GetField<int>(obj, "rating"), JsonRpcClient.GetField<string>(obj, "album", string.Empty), JsonRpcClient.GetField<int>(obj, "track"), //JsonRpcClient.GetField<int>(obj, "tracknumber"), //JsonRpcClient.GetField<int>(obj, "discnumber"), JsonRpcClient.GetField<int>(obj, "duration"), JsonRpcClient.GetField<string>(obj, "comment", string.Empty), JsonRpcClient.GetField<string>(obj, "lyrics", string.Empty)); } catch (Exception ex) { if (logger != null) logger.LogErrorMessage("EXCEPTION in XbmcSong.FromJson()!!!", ex); return null; } }
internal XbmcGeneral(JsonRpcClient client) : base(client) { this.system = new XbmcSystem(client); }
internal XbmcSystem(JsonRpcClient client) : base(client) { }
internal XbmcAudioLibrary(JsonRpcClient client) : base("AudioLibrary", client) { }
internal XbmcAudioPlayer(JsonRpcClient client) : base("AudioPlayer", "MusicPlayer", client, 0) { }
private void SendRequestsAndWait(JsonRpcClient client, IObservable<JObject> requestStream) { // chaining is fun var mre = new ManualResetEventSlim(false); using ((from request in requestStream select client.Invoke<Newtonsoft.Json.Linq.JObject>("testArbitraryJObject", request, Scheduler.TaskPool)) .Merge() .Subscribe( onNext: _ => { /* do nothing and like it */ }, onError: _ => {Debug.WriteLine(_.Message); mre.Set();}, onCompleted: mre.Set)) { mre.Wait(); } }
internal static XbmcVideo FromJson(JObject obj, JsonRpcClient logger) { if (obj == null) { return null; } try { string type; if (obj["type"] == null) type = "unknown"; else type = JsonRpcClient.GetField<string>(obj, "type"); if (logger != null) logger.LogMessage("Trying to identify " + type); if ("episode" == type) return XbmcTvEpisode.FromJson(obj, logger); if ("musicvideo" == type) return XbmcMusicVideo.FromJson(obj, logger); if ("movie" == type) return XbmcMovie.FromJson(obj, logger); // Otherwise try a movie //else if () //{ if (logger != null) logger.LogMessage("Trying to identify Unhandled type of media as movie"); return XbmcMovie.FromJson(obj, logger); //} } catch (Exception ex) { if (logger != null) logger.LogErrorMessage("EXCEPTION in XbmcVideo.FromJson()!!!", ex); return null; } }
internal XbmcJsonRpc(JsonRpcClient client) : base(client) { }
public async Task ExecuteCommand(Command cmd, Parameters parameters = null) { cmd.Updating = true; if (parameters == null) { parameters = new Parameters(); parameters.id = cmd.id; parameters.name = cmd.name; } var jsonrpc = new JsonRpcClient(parameters); if (await jsonrpc.SendRequest("cmd::execCmd")) { var response = jsonrpc.GetRequestResponseDeserialized<Response<CommandResult>>(); cmd.Value = response.result.value; } else { cmd.Value = "N/A"; } cmd.Updating = false; }