<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Mono.Posix" />
+ <Reference Include="jsonrpc4net">
+ <HintPath>..\..\jsonrpc4net\jsonrpc4net\bin\Debug\jsonrpc4net.dll</HintPath>
+ </Reference>
+ <Reference Include="log4net">
+ <HintPath>..\..\..\..\..\..\..\usr\mymono\custom\log4net-1.2.13\cli\1.0\log4net.dll</HintPath>
+ </Reference>
<Reference Include="System.Net.Http">
- <HintPath>..\..\..\..\..\..\..\..\usr\mymono\lib\mono\4.5\System.Net.Http.dll</HintPath>
+ <HintPath>..\..\..\..\..\..\..\usr\mymono\lib\mono\4.5\System.Net.Http.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=c7439020c8fedf87">
<Package>monodevelop</Package>
<Private>True</Private>
</Reference>
- <Reference Include="log4net">
- <HintPath>..\..\..\..\..\..\..\usr\mymono\custom\log4net-1.2.13\cli\1.0\log4net.dll</HintPath>
- </Reference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="gtk-gui\gui.stetic">
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ViewModel\ViewModel.cs" />
- <Compile Include="Model\CallRemoteProcedure.cs" />
<Compile Include="MainWindow.cs">
<DependentUpon>Program.cs</DependentUpon>
</Compile>
using System;
using Gtk;
-using System.Net.Http;
using System.Threading.Tasks;
using Example.RemoteAgents.GTKLinux.View;
using log4net;
{
public partial class MainWindow: Gtk.Window
{
- ViewImpl view;
+ private readonly ViewImpl _view;
private static readonly ILog logger = LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public MainWindow () : base (Gtk.WindowType.Toplevel)
{
- view = new ViewImpl();
+ _view = new ViewImpl();
Build ();
- this.RetrieveRemoteDateButton.Clicked += this.ButtonClicked;
this.ButtonGetDate.Clicked += this.ButtonGetDateClicked;
}
a.RetVal = true;
}
- async private void ButtonClicked(object sender, EventArgs a)
- {
- using (HttpClient client = new HttpClient ()) {
- Task<string> resultGET = client.GetStringAsync ("http://gumartinm.name");
- this.RemoteDate.Buffer.Text = await resultGET;
- }
- }
-
async private void ButtonGetDateClicked(object sender, EventArgs a)
{
try {
- string currentDate = await view.GetCurrentDateAsync();
+ string currentDate = await _view.GetCurrentDateAsync();
if (currentDate != null)
{
this.RemoteDate.Buffer.Text = currentDate;
+++ /dev/null
-using System;
-using System.Net;
-using System.Net.Http;
-using System.Reflection;
-using System.Runtime.Remoting.Lifetime;
-using System.Runtime.Remoting.Messaging;
-using System.Security.Cryptography.X509Certificates;
-using System.Threading.Tasks;
-using Gtk;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Converters;
-using Newtonsoft.Json.Serialization;
-using System.Threading;
-using log4net;
-
-namespace Example.RemoteAgents.GTKLinux.Model
-{
- public class CallRemoteProcedure
- {
- private static readonly ILog logger = LogManager.GetLogger(
- System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
-
- async public Task<TResult> PostRemoteServiceAsync<TResult>(string uri, string method)
- {
- POSTResult<TResult> postResult = await this.PostAsync<TResult>(uri, method, CancellationToken.None);
-
- return postResult.result;
- }
-
- async private Task<POSTResult<TResult>> PostAsync<TResult>(string uri, string method, CancellationToken cancellation)
- {
- var postData = new POST();
- postData.id = "2114567586433855105";
- postData.jsonrpc = "2.0";
- postData.method = method;
- var jsonSettings = new JsonSerializerSettings{
- Error = delegate(object sender, ErrorEventArgs args)
- {
- logger.Error(args.ErrorContext.Error.Message);
- args.ErrorContext.Handled = true;
- }
- };
-
- string data = JsonConvert.SerializeObject(postData, jsonSettings);
-
- // see: http://stackoverflow.com/questions/1329739/nested-using-statements-in-c-sharp
- // see: http://stackoverflow.com/questions/5895879/when-do-we-need-to-call-dispose-in-dot-net-c
- //TODO: Am I really sure I have to call the Dispose method of HttpContent content. In this case shouldn't it be stupid?
- // for HttpResponseMessage response I am sure I have to do it but I am not for HttpContent content.
- using (HttpContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json-rpc"))
- using (HttpResponseMessage response = await this.PostAsync(uri, content, cancellation))
- {
- POSTResult<TResult> postResult = new POSTResult<TResult>();
-
- if (response.StatusCode == HttpStatusCode.OK) {
- byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
- string responseString = System.Text.Encoding.UTF8.GetString(responseBytes);
-
- postResult = JsonConvert.DeserializeObject<POSTResult<TResult>>(responseString, jsonSettings);
- }
-
- return postResult;
- }
- }
-
- /// <summary>
- /// Send a POST request to the specified Uri as an asynchronous operation.
- /// </summary>
- /// <param name="uri">The Uri the request is sent to.</param>
- /// <param name="content">The HTTP request content sent to the server.</param>
- /// <param name="System.Threading.CancellationToken">Cancellation token.</param>
- /// <exception cref="System.InvalidOperationException">When some error.</exception>
- /// <returns>System.Threading.Tasks.Task<![CDATA[<TResult>]]>.The task object representing the asynchronous operation.</returns>
- async private Task<HttpResponseMessage> PostAsync(string uri, HttpContent content, CancellationToken cancellation)
- {
- using (HttpClient client = new HttpClient{ Timeout = TimeSpan.FromSeconds(5)})
- {
- return await client.PostAsync(uri, content, cancellation);
- }
- }
-
- private class POST
- {
- public string id { get; set; }
- public string jsonrpc { get; set; }
- public string method { get; set; }
- }
-
-
- private class POSTResult<TResult>
- {
- public string id { get; set; }
- public string jsonrpc { get; set; }
- public TResult result { get; set; }
- }
-
- // TODO: When error I receive from JSONRPC: {"jsonrpc":"2.0","id":"null","error":{"code":-32600,"message":"Invalid Request"}}
- private class Error
- {
- public int code { get; set; }
- public string message { get; set; }
- }
-
- private class ERRORResult
- {
- public string jsonrpc { get; set; }
- public string id { get; set; }
- public Error error { get; set; }
- }
- }
-}
-
{
public class ViewImpl
{
- private static readonly ViewModelImpl vm = new ViewModelImpl();
+ private readonly ViewModelImpl _vm = new ViewModelImpl();
async public Task<string> GetCurrentDateAsync()
{
- return await vm.GetCurrentDateAsync();
+ return await _vm.GetCurrentDateAsync();
}
}
}
using System;
using System.Threading.Tasks;
-using Example.RemoteAgents.GTKLinux.Model;
+using GumartinM.JsonRPC4Mono;
+using System.ComponentModel;
namespace Example.RemoteAgents.GTKLinux.ViewModel
{
public class ViewModelImpl
{
- private static readonly string uri = "http://gumartinm.name/spring-mainapp/CurrentDateService.json";
- private readonly CallRemoteProcedure remoteProcedure = new CallRemoteProcedure();
+ private static readonly string uri = "http://127.0.0.1:8080/spring-mainapp/CurrentDateService.json";
+ private readonly JsonRpcHttpAsyncClient _remoteClient = new JsonRpcHttpAsyncClient();
async public Task<string> GetCurrentDateAsync()
{
- return await remoteProcedure.PostRemoteServiceAsync<string>(uri, "getCurrentDate");
+ return await _remoteClient.PostRemoteServiceAsync<string>(uri, "getCurrentDate");
}
}
}
--- /dev/null
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2012
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "jsonrpc4net", "jsonrpc4net\jsonrpc4net.csproj", "{0C624E8F-9C80-457F-A7D1-39FA29E23F79}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {0C624E8F-9C80-457F-A7D1-39FA29E23F79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0C624E8F-9C80-457F-A7D1-39FA29E23F79}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0C624E8F-9C80-457F-A7D1-39FA29E23F79}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0C624E8F-9C80-457F-A7D1-39FA29E23F79}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(MonoDevelopProperties) = preSolution
+ StartupItem = jsonrpc4net\jsonrpc4net.csproj
+ description = jsonrpc4net library implementation (just for fun)
+ EndGlobalSection
+EndGlobal
--- /dev/null
+using System;
+using Newtonsoft.Json.Linq;
+using System.Collections.Generic;
+
+namespace GumartinM.JsonRPC4Mono
+{
+ public class ExceptionResolver
+ {
+ /// <summary>
+ /// Resolves the exception.
+ /// </summary>
+ /// <returns>The exception.</returns>
+ /// <param name="errorToken">Error token.</param>
+ public Exception ResolveException(JToken errorToken)
+ {
+ JObject errorData = (JObject) errorToken;
+ IDictionary<string, JToken> errorTokens = errorData;
+
+ if (!errorTokens.ContainsKey("data"))
+ {
+ return CreateJsonRpcClientException(errorToken);
+ }
+
+ JToken dataToken = errorToken["data"];
+ JObject data = (JObject) dataToken;
+ errorTokens = data;
+
+ if (!errorTokens.ContainsKey("exceptionTypeName"))
+ {
+ return CreateJsonRpcClientException(errorToken);
+ }
+
+ string exceptionTypeName = data["exceptionTypeName"].Value<string>();
+ string message = data.Value<string>("message");
+
+ Exception endException = CreateException(exceptionTypeName, message);
+
+ return endException;
+ }
+
+ /// <summary>
+ /// Creates the json rpc client exception.
+ /// </summary>
+ /// <returns>The json rpc client exception.</returns>
+ /// <param name="errorToken">Error token.</param>
+ private JsonRpcClientException CreateJsonRpcClientException(JToken errorToken)
+ {
+ return new JsonRpcClientException(
+ errorToken.Value<int?>("code") ?? 0,
+ errorToken.Value<string>("message"),
+ errorToken.SelectToken("data"));
+ }
+
+ /// <summary>
+ /// Creates the exception.
+ /// </summary>
+ /// <returns>The exception.</returns>
+ /// <param name="exceptionTypeName">Exception type name.</param>
+ /// <param name="message">Message.</param>
+ private Exception CreateException(string exceptionTypeName, string message)
+ {
+ return new Exception("Remote exception: " + exceptionTypeName + "Message: " + message);
+ }
+ }
+}
+
--- /dev/null
+using System;
+using System.Runtime.Serialization;
+using Newtonsoft.Json.Linq;
+
+namespace GumartinM.JsonRPC4Mono
+{
+ public class JsonRpcClientException : System.Exception, ISerializable
+ {
+ /// <summary>
+ /// The _code.
+ /// </summary>
+ private readonly int _code;
+
+ /// <summary>
+ /// The _data.
+ /// </summary>
+ private readonly JToken _data;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Example.RemoteAgents.GTKLinux.Model.JsonRpcClientException"/> class.
+ /// </summary>
+ /// <param name="code">Code.</param>
+ /// <param name="message">Message.</param>
+ /// <param name="data">Data.</param>
+ public JsonRpcClientException(int code, String message, JToken data) : base(message)
+ {
+ _code = code;
+ _data = data;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Example.RemoteAgents.GTKLinux.Model.JsonRpcClientException"/> class.
+ /// </summary>
+ /// <param name="info">Info.</param>
+ /// <param name="context">Context.</param>
+ protected JsonRpcClientException(SerializationInfo info, StreamingContext context)
+ {
+ // TODO
+ }
+
+ /// <summary>
+ /// Gets the code.
+ /// </summary>
+ /// <returns>The code.</returns>
+ public int getCode() {
+ return _code;
+ }
+
+ /// <summary>
+ /// Gets the data.
+ /// </summary>
+ /// <returns>The data.</returns>
+ public JToken getData() {
+ return _data;
+ }
+ }
+}
+
--- /dev/null
+using System;
+using System.Net.Http;
+using System.Threading.Tasks;
+using System.Threading;
+using log4net;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Serialization;
+using System.Net;
+using Newtonsoft.Json.Linq;
+using System.Collections.Generic;
+
+namespace GumartinM.JsonRPC4Mono
+{
+ public class JsonRpcHttpAsyncClient
+ {
+ private long _nextId;
+
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private static readonly ILog logger = LogManager.GetLogger(
+ System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
+
+ /// <summary>
+ /// The _json settings.
+ /// </summary>
+ private readonly JsonSerializerSettings _jsonSettings =
+ new JsonSerializerSettings{
+ Error = delegate(object sender, ErrorEventArgs args)
+ {
+ logger.Error(args.ErrorContext.Error.Message);
+ args.ErrorContext.Handled = true;
+ }
+ };
+
+ /// <summary>
+ /// The _exception resolver.
+ /// </summary>
+ private readonly ExceptionResolver _exceptionResolver = new ExceptionResolver();
+
+
+
+ /// <summary>
+ /// Posts the remote service async.
+ /// </summary>
+ /// <returns>The remote service async.</returns>
+ /// <param name="uri">URI.</param>
+ /// <param name="method">Method.</param>
+ /// <typeparam name="TResult">The 1st type parameter.</typeparam>
+ async public Task<TResult> PostRemoteServiceAsync<TResult>(string uri, string method)
+ {
+ POSTResult<TResult> postResult = await this.PostAsync<TResult>(uri, method, CancellationToken.None);
+
+ return postResult.result;
+ }
+
+ /// <summary>
+ /// Posts the async.
+ /// </summary>
+ /// <returns>The async.</returns>
+ /// <param name="uri">URI.</param>
+ /// <param name="method">Method.</param>
+ /// <param name="cancellation">Cancellation.</param>
+ /// <typeparam name="TResult">The 1st type parameter.</typeparam>
+ async private Task<POSTResult<TResult>> PostAsync<TResult>(string uri, string method, CancellationToken cancellation)
+ {
+ var postData = new POST();
+ postData.id = Interlocked.Increment(ref _nextId).ToString();
+ postData.jsonrpc = "2.0";
+ postData.method = method;
+
+ string data = JsonConvert.SerializeObject(postData, _jsonSettings);
+
+ // see: http://stackoverflow.com/questions/1329739/nested-using-statements-in-c-sharp
+ // see: http://stackoverflow.com/questions/5895879/when-do-we-need-to-call-dispose-in-dot-net-c
+ //TODO: Am I really sure I have to call the Dispose method of HttpContent content? In this case, shouldn't it be stupid?
+ // For HttpResponseMessage response I am sure I have to do it but I am not for HttpContent content.
+ using (HttpContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json-rpc"))
+ using (HttpResponseMessage response = await this.PostAsync(uri, content, cancellation))
+ {
+
+ if (response.StatusCode == HttpStatusCode.OK) {
+ byte[] jsonBytes = await response.Content.ReadAsByteArrayAsync();
+
+ return this.ReadResponse<TResult>(jsonBytes);
+ }
+
+ throw new Exception("Unexpected response code: " + response.StatusCode);
+ }
+ }
+
+ /// <summary>
+ /// Reads the response.
+ /// </summary>
+ /// <returns>The response.</returns>
+ /// <param name="jsonBytes">Json bytes.</param>
+ /// <typeparam name="TResult">The 1st type parameter.</typeparam>
+ private POSTResult<TResult> ReadResponse<TResult>(byte[] jsonBytes)
+ {
+ POSTResult<TResult> postResult = new POSTResult<TResult>();
+
+ string json = System.Text.Encoding.UTF8.GetString(jsonBytes);
+
+ JObject jsonObjects = JObject.Parse(json);
+ IDictionary<string, JToken> jsonTokens = jsonObjects;
+
+
+ if (jsonTokens.ContainsKey("error"))
+ {
+ throw _exceptionResolver.ResolveException(jsonObjects["error"]);
+ }
+
+ if (jsonTokens.ContainsKey("result"))
+ {
+ postResult = JsonConvert.DeserializeObject<POSTResult<TResult>>(json, _jsonSettings);
+ }
+
+ return postResult;
+ }
+
+ /// <summary>
+ /// Send a POST request to the specified Uri as an asynchronous operation.
+ /// </summary>
+ /// <param name="uri">The Uri the request is sent to.</param>
+ /// <param name="content">The HTTP request content sent to the server.</param>
+ /// <param name="System.Threading.CancellationToken">Cancellation token.</param>
+ /// <exception cref="System.InvalidOperationException">When some error.</exception>
+ /// <returns>System.Threading.Tasks.Task<![CDATA[<TResult>]]>.The task object representing the asynchronous operation.</returns>
+ async private Task<HttpResponseMessage> PostAsync(string uri, HttpContent content, CancellationToken cancellation)
+ {
+ using (HttpClient client = new HttpClient{ Timeout = TimeSpan.FromSeconds(5)})
+ {
+ // TODO: cancellation
+ return await client.PostAsync(uri, content, cancellation);
+ }
+ }
+
+ private class POST
+ {
+ public string id { get; set; }
+ public string jsonrpc { get; set; }
+ public string method { get; set; }
+ }
+
+
+ private class POSTResult<TResult>
+ {
+ public string id { get; set; }
+ public string jsonrpc { get; set; }
+ public TResult result { get; set; }
+ }
+ }
+}
+
--- /dev/null
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+// Information about this assembly is defined by the following attributes.
+// Change them to the values specific to your project.
+[assembly: AssemblyTitle("jsonrpc4net")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("")]
+[assembly: AssemblyCopyright("gustavo")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
+// The form "{Major}.{Minor}.*" will automatically update the build and revision,
+// and "{Major}.{Minor}.{Build}.*" will update just the revision.
+[assembly: AssemblyVersion("1.0.*")]
+// The following attributes are used to specify the signing key for the assembly,
+// if desired. See the Mono documentation for more information about signing.
+//[assembly: AssemblyDelaySign(false)]
+//[assembly: AssemblyKeyFile("")]
+
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>12.0.0</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{0C624E8F-9C80-457F-A7D1-39FA29E23F79}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <RootNamespace>GumartinM.JsonRPC4Mono</RootNamespace>
+ <AssemblyName>jsonrpc4net</AssemblyName>
+ <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <Description>Dirty implementation of JSON RPC. Just trying to learn how
+to use C#.</Description>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug</OutputPath>
+ <DefineConstants>DEBUG;</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <ConsolePause>false</ConsolePause>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>full</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release</OutputPath>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <ConsolePause>false</ConsolePause>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ <Reference Include="System.Net.Http">
+ <HintPath>..\..\..\..\..\..\..\usr\mymono\lib\mono\4.5\System.Net.Http.dll</HintPath>
+ </Reference>
+ <Reference Include="log4net">
+ <HintPath>..\..\..\..\..\..\..\usr\mymono\custom\log4net-1.2.13\cli\1.0\log4net.dll</HintPath>
+ </Reference>
+ <Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=c7439020c8fedf87">
+ <Package>monodevelop</Package>
+ </Reference>
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="JsonRpcHttpAsyncClient.cs" />
+ <Compile Include="ExceptionResolver.cs" />
+ <Compile Include="JsonRpcClientException.cs" />
+ </ItemGroup>
+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+</Project>
\ No newline at end of file