From: gu.martinm@gmail.com Date: Mon, 3 Mar 2014 13:08:41 +0000 (+0100) Subject: JSONRPC4NET: same project Linux and WP8 X-Git-Url: https://git.gumartinm.name/?a=commitdiff_plain;h=6d901639c64caff208a8091be448dd61bca0bb1b;p=CSharpForFun%2F.git JSONRPC4NET: same project Linux and WP8 --- diff --git a/Mono/RemoteAgents/GTKLinux/GTKLinux.csproj b/Mono/RemoteAgents/GTKLinux/GTKLinux.csproj index feea786..27e0f6f 100644 --- a/Mono/RemoteAgents/GTKLinux/GTKLinux.csproj +++ b/Mono/RemoteAgents/GTKLinux/GTKLinux.csproj @@ -55,13 +55,13 @@ through JSON API. - ..\..\jsonrpc4net\jsonrpc4net\bin\Debug\jsonrpc4net.dll - - - ..\..\..\..\..\..\..\usr\mymono\custom\log4net-1.2.13\cli\1.0\log4net.dll + ..\..\..\jsonrpc4net\jsonrpc4net\bin\Debug\jsonrpc4net.dll - ..\..\..\..\..\..\..\usr\mymono\lib\mono\4.5\System.Net.Http.dll + ..\..\..\..\..\..\..\..\usr\mymono\lib\mono\4.5\System.Net.Http.dll + + + ..\..\..\ThirdParty\Libs\NLog\net45\NLog.dll monodevelop @@ -90,9 +90,4 @@ through JSON API. - - - PreserveNewest - - - \ No newline at end of file + diff --git a/Mono/RemoteAgents/GTKLinux/Log4Net.config b/Mono/RemoteAgents/GTKLinux/Log4Net.config deleted file mode 100644 index 680ab43..0000000 --- a/Mono/RemoteAgents/GTKLinux/Log4Net.config +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/Mono/RemoteAgents/GTKLinux/MainWindow.cs b/Mono/RemoteAgents/GTKLinux/MainWindow.cs index 6e5498c..04c7d98 100644 --- a/Mono/RemoteAgents/GTKLinux/MainWindow.cs +++ b/Mono/RemoteAgents/GTKLinux/MainWindow.cs @@ -2,15 +2,14 @@ using Gtk; using System.Threading.Tasks; using Example.RemoteAgents.GTKLinux.View; -using log4net; +using NLog; namespace Example.RemoteAgents.GTKLinux { public partial class MainWindow: Gtk.Window { private readonly ViewImpl _view; - private static readonly ILog logger = LogManager.GetLogger( - System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public MainWindow () : base (Gtk.WindowType.Toplevel) { @@ -28,11 +27,7 @@ namespace Example.RemoteAgents.GTKLinux async private void ButtonGetDateClicked(object sender, EventArgs a) { try { - string currentDate = await _view.GetCurrentDateAsync(); - if (currentDate != null) - { - this.RemoteDate.Buffer.Text = currentDate; - } + this.RemoteDate.Buffer.Text = await _view.GetCurrentDateAsync(); } catch (Exception e) { diff --git a/Mono/RemoteAgents/GTKLinux/Properties/AssemblyInfo.cs b/Mono/RemoteAgents/GTKLinux/Properties/AssemblyInfo.cs index 9d9a201..db7d778 100644 --- a/Mono/RemoteAgents/GTKLinux/Properties/AssemblyInfo.cs +++ b/Mono/RemoteAgents/GTKLinux/Properties/AssemblyInfo.cs @@ -18,5 +18,4 @@ using System.Runtime.CompilerServices; // 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("")] -[assembly: log4net.Config.XmlConfigurator(ConfigFile="Log4Net.config", Watch=true)] +//[assembly: AssemblyKeyFile("")] \ No newline at end of file diff --git a/Mono/RemoteAgents/GTKLinux/ViewModel/ViewModel.cs b/Mono/RemoteAgents/GTKLinux/ViewModel/ViewModel.cs index 704fe6b..e8dda29 100644 --- a/Mono/RemoteAgents/GTKLinux/ViewModel/ViewModel.cs +++ b/Mono/RemoteAgents/GTKLinux/ViewModel/ViewModel.cs @@ -1,6 +1,6 @@ using System; using System.Threading.Tasks; -using GumartinM.JsonRPC4Mono; +using GumartinM.JsonRPC4NET; using System.ComponentModel; namespace Example.RemoteAgents.GTKLinux.ViewModel diff --git a/Mono/jsonrpc4net/jsonrpc4net.sln b/Mono/jsonrpc4net/jsonrpc4net.sln deleted file mode 100644 index 41c9388..0000000 --- a/Mono/jsonrpc4net/jsonrpc4net.sln +++ /dev/null @@ -1,21 +0,0 @@ - -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 diff --git a/Mono/jsonrpc4net/jsonrpc4net/ExceptionResolver.cs b/Mono/jsonrpc4net/jsonrpc4net/ExceptionResolver.cs deleted file mode 100644 index 81b8d81..0000000 --- a/Mono/jsonrpc4net/jsonrpc4net/ExceptionResolver.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using Newtonsoft.Json.Linq; -using System.Collections.Generic; - -namespace GumartinM.JsonRPC4Mono -{ - public class ExceptionResolver - { - /// - /// Resolves the exception. - /// - /// The exception. - /// Error token. - public Exception ResolveException(JToken errorToken) - { - JObject errorData = (JObject) errorToken; - IDictionary 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 message = data.Value("message"); - - Exception endException = CreateException(exceptionTypeName, message); - - return endException; - } - - /// - /// Creates the json rpc client exception. - /// - /// The json rpc client exception. - /// Error token. - private JsonRpcClientException CreateJsonRpcClientException(JToken errorToken) - { - return new JsonRpcClientException( - errorToken.Value("code") ?? 0, - errorToken.Value("message"), - errorToken.SelectToken("data")); - } - - /// - /// Creates the exception. - /// - /// The exception. - /// Exception type name. - /// Message. - private Exception CreateException(string exceptionTypeName, string message) - { - return new Exception("Remote exception: " + exceptionTypeName + "Message: " + message); - } - } -} - diff --git a/Mono/jsonrpc4net/jsonrpc4net/JsonRpcClientException.cs b/Mono/jsonrpc4net/jsonrpc4net/JsonRpcClientException.cs deleted file mode 100644 index 31b7985..0000000 --- a/Mono/jsonrpc4net/jsonrpc4net/JsonRpcClientException.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Runtime.Serialization; -using Newtonsoft.Json.Linq; - -namespace GumartinM.JsonRPC4Mono -{ - public class JsonRpcClientException : System.Exception, ISerializable - { - /// - /// The _code. - /// - private readonly int _code; - - /// - /// The _data. - /// - private readonly JToken _data; - - /// - /// Initializes a new instance of the class. - /// - /// Code. - /// Message. - /// Data. - public JsonRpcClientException(int code, String message, JToken data) : base(message) - { - _code = code; - _data = data; - } - - /// - /// Initializes a new instance of the class. - /// - /// Info. - /// Context. - protected JsonRpcClientException(SerializationInfo info, StreamingContext context) - { - // TODO - } - - /// - /// Gets the code. - /// - /// The code. - public int getCode() { - return _code; - } - - /// - /// Gets the data. - /// - /// The data. - public JToken getData() { - return _data; - } - } -} - diff --git a/Mono/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs b/Mono/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs deleted file mode 100644 index 56469e0..0000000 --- a/Mono/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs +++ /dev/null @@ -1,152 +0,0 @@ -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; - - /// - /// The logger. - /// - private static readonly ILog logger = LogManager.GetLogger( - System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// The _json settings. - /// - private readonly JsonSerializerSettings _jsonSettings = - new JsonSerializerSettings{ - Error = delegate(object sender, ErrorEventArgs args) - { - logger.Error(args.ErrorContext.Error.Message); - args.ErrorContext.Handled = true; - } - }; - - /// - /// The _exception resolver. - /// - private readonly ExceptionResolver _exceptionResolver = new ExceptionResolver(); - - - - /// - /// Posts the remote service async. - /// - /// The remote service async. - /// URI. - /// Method. - /// The 1st type parameter. - async public Task PostRemoteServiceAsync(string uri, string method) - { - POSTResult postResult = await this.PostAsync(uri, method, CancellationToken.None); - - return postResult.result; - } - - /// - /// Posts the async. - /// - /// The async. - /// URI. - /// Method. - /// Cancellation. - /// The 1st type parameter. - async private Task> PostAsync(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(jsonBytes); - } - - throw new Exception("Unexpected response code: " + response.StatusCode); - } - } - - /// - /// Reads the response. - /// - /// The response. - /// Json bytes. - /// The 1st type parameter. - private POSTResult ReadResponse(byte[] jsonBytes) - { - string json = System.Text.Encoding.UTF8.GetString(jsonBytes); - - JObject jsonObjects = JObject.Parse(json); - IDictionary jsonTokens = jsonObjects; - - - if (jsonTokens.ContainsKey("error")) - { - throw _exceptionResolver.ResolveException(jsonObjects["error"]); - } - - if (jsonTokens.ContainsKey("result")) - { - return JsonConvert.DeserializeObject>(json, _jsonSettings); - } - - throw new JsonRpcClientException(0, "There is not neither error nor result in JSON response data.", jsonObjects); - } - - /// - /// Send a POST request to the specified Uri as an asynchronous operation. - /// - /// The Uri the request is sent to. - /// The HTTP request content sent to the server. - /// Cancellation token. - /// When some error. - /// System.Threading.Tasks.Task]]>.The task object representing the asynchronous operation. - async private Task 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 - { - public string id { get; set; } - public string jsonrpc { get; set; } - public TResult result { get; set; } - } - } -} - diff --git a/Mono/jsonrpc4net/jsonrpc4net/Properties/AssemblyInfo.cs b/Mono/jsonrpc4net/jsonrpc4net/Properties/AssemblyInfo.cs deleted file mode 100644 index c842ef8..0000000 --- a/Mono/jsonrpc4net/jsonrpc4net/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -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("")] - diff --git a/Mono/jsonrpc4net/jsonrpc4net/jsonrpc4net.csproj b/Mono/jsonrpc4net/jsonrpc4net/jsonrpc4net.csproj deleted file mode 100644 index 1de2357..0000000 --- a/Mono/jsonrpc4net/jsonrpc4net/jsonrpc4net.csproj +++ /dev/null @@ -1,53 +0,0 @@ - - - - Debug - AnyCPU - 12.0.0 - 2.0 - {0C624E8F-9C80-457F-A7D1-39FA29E23F79} - Library - GumartinM.JsonRPC4Mono - jsonrpc4net - v4.5 - Dirty implementation of JSON RPC. Just trying to learn how -to use C#. - - - true - full - false - bin\Debug - DEBUG; - prompt - 4 - false - - - full - true - bin\Release - prompt - 4 - false - - - - - ..\..\..\..\..\..\..\usr\mymono\lib\mono\4.5\System.Net.Http.dll - - - ..\..\..\..\..\..\..\usr\mymono\custom\log4net-1.2.13\cli\1.0\log4net.dll - - - monodevelop - - - - - - - - - - \ No newline at end of file diff --git a/WindowsPhone/jsonrpc4net/jsonrpc4net.sln b/WindowsPhone/jsonrpc4net/jsonrpc4net.sln deleted file mode 100644 index a7aa75e..0000000 --- a/WindowsPhone/jsonrpc4net/jsonrpc4net.sln +++ /dev/null @@ -1,34 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.30110.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "jsonrpc4net", "jsonrpc4net\jsonrpc4net.csproj", "{9FC57CC3-23D0-486B-A3E4-92C547561949}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|ARM = Debug|ARM - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|ARM = Release|ARM - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|ARM.ActiveCfg = Debug|ARM - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|ARM.Build.0 = Debug|ARM - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|x86.ActiveCfg = Debug|x86 - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|x86.Build.0 = Debug|x86 - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|Any CPU.Build.0 = Release|Any CPU - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|ARM.ActiveCfg = Release|ARM - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|ARM.Build.0 = Release|ARM - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|x86.ActiveCfg = Release|x86 - {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/WindowsPhone/jsonrpc4net/jsonrpc4net/ExceptionResolver.cs b/WindowsPhone/jsonrpc4net/jsonrpc4net/ExceptionResolver.cs deleted file mode 100644 index 391b25d..0000000 --- a/WindowsPhone/jsonrpc4net/jsonrpc4net/ExceptionResolver.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; - -namespace GumartinM.JsonRPC4Mono -{ - public class ExceptionResolver - { - /// - /// Resolves the exception. - /// - /// The exception. - /// Error token. - public Exception ResolveException(JToken errorToken) - { - JObject errorData = (JObject)errorToken; - IDictionary 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 message = data.Value("message"); - - Exception endException = CreateException(exceptionTypeName, message); - - return endException; - } - - /// - /// Creates the json rpc client exception. - /// - /// The json rpc client exception. - /// Error token. - private JsonRpcClientException CreateJsonRpcClientException(JToken errorToken) - { - return new JsonRpcClientException( - errorToken.Value("code") ?? 0, - errorToken.Value("message"), - errorToken.SelectToken("data")); - } - - /// - /// Creates the exception. - /// - /// The exception. - /// Exception type name. - /// Message. - private Exception CreateException(string exceptionTypeName, string message) - { - return new Exception("Remote exception: " + exceptionTypeName + "Message: " + message); - } - } -} diff --git a/WindowsPhone/jsonrpc4net/jsonrpc4net/JsonRpcClientException.cs b/WindowsPhone/jsonrpc4net/jsonrpc4net/JsonRpcClientException.cs deleted file mode 100644 index c64ad22..0000000 --- a/WindowsPhone/jsonrpc4net/jsonrpc4net/JsonRpcClientException.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Newtonsoft.Json.Linq; -using System; - -namespace GumartinM.JsonRPC4Mono -{ - public class JsonRpcClientException : System.Exception - { - /// - /// The _code. - /// - private readonly int _code; - - /// - /// The _data. - /// - private readonly JToken _data; - - /// - /// Initializes a new instance of the class. - /// - /// Code. - /// Message. - /// Data. - public JsonRpcClientException(int code, String message, JToken data) - : base(message) - { - _code = code; - _data = data; - } - - /// - /// Gets the code. - /// - /// The code. - public int getCode() - { - return _code; - } - - /// - /// Gets the data. - /// - /// The data. - public JToken getData() - { - return _data; - } - } -} diff --git a/WindowsPhone/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs b/WindowsPhone/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs deleted file mode 100644 index c092859..0000000 --- a/WindowsPhone/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs +++ /dev/null @@ -1,155 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; -using NLog; -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; - -namespace GumartinM.JsonRPC4Mono -{ - public class JsonRpcHttpAsyncClient - { - /// - /// RPC call id. - /// - private long _nextId; - - /// - /// The logger. - /// - private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); - - /// - /// The _json settings. - /// - private readonly JsonSerializerSettings _jsonSettings = - new JsonSerializerSettings - { - Error = delegate(object sender, ErrorEventArgs args) - { - _logger.Error(args.ErrorContext.Error.Message); - args.ErrorContext.Handled = true; - } - }; - - /// - /// The _exception resolver. - /// - private readonly ExceptionResolver _exceptionResolver = new ExceptionResolver(); - - - - /// - /// Posts the remote service async. - /// - /// The remote service async. - /// URI. - /// Method. - /// The 1st type parameter. - async public Task PostRemoteServiceAsync(string uri, string method) - { - POSTResult postResult = await this.PostAsync(uri, method, CancellationToken.None); - - return postResult.result; - } - - /// - /// Posts the async. - /// - /// The async. - /// URI. - /// Method. - /// Cancellation. - /// The 1st type parameter. - async private Task> PostAsync(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(jsonBytes); - } - - throw new Exception("Unexpected response code: " + response.StatusCode); - } - } - - /// - /// Reads the response. - /// - /// The response. - /// Json bytes. - /// The 1st type parameter. - private POSTResult ReadResponse(byte[] jsonBytes) - { - string json = System.Text.Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length); - - JObject jsonObjects = JObject.Parse(json); - IDictionary jsonTokens = jsonObjects; - - - if (jsonTokens.ContainsKey("error")) - { - throw _exceptionResolver.ResolveException(jsonObjects["error"]); - } - - if (jsonTokens.ContainsKey("result")) - { - return JsonConvert.DeserializeObject>(json, _jsonSettings); - } - - throw new JsonRpcClientException(0, "There is not neither error nor result in JSON response data.", jsonObjects); - } - - /// - /// Send a POST request to the specified Uri as an asynchronous operation. - /// - /// The Uri the request is sent to. - /// The HTTP request content sent to the server. - /// Cancellation token. - /// When some error. - /// System.Threading.Tasks.Task]]>.The task object representing the asynchronous operation. - async private Task 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 - { - public string id { get; set; } - public string jsonrpc { get; set; } - public TResult result { get; set; } - } - } -} diff --git a/WindowsPhone/jsonrpc4net/jsonrpc4net/Properties/AssemblyInfo.cs b/WindowsPhone/jsonrpc4net/jsonrpc4net/Properties/AssemblyInfo.cs deleted file mode 100644 index 992223a..0000000 --- a/WindowsPhone/jsonrpc4net/jsonrpc4net/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Resources; - -// La información general de un ensamblado se controla mediante el siguiente -// conjunto de atributos. Cambie los valores de estos atributos para modificar la información -// asociada a un ensamblado. -[assembly: AssemblyTitle("jsonrpc4net")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("jsonrpc4net")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Si ComVisible se establece en False, los componentes COM no verán los -// tipos de este ensamblado. Si necesita obtener acceso a un tipo de este ensamblado desde -// COM, establezca el atributo ComVisible en True en este tipo. -[assembly: ComVisible(false)] - -// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM -[assembly: Guid("9fc57cc3-23d0-486b-a3e4-92c547561949")] - -// La información de versión de un ensamblado consta de los cuatro valores siguientes: -// -// Versión principal -// Versión secundaria -// Número de compilación -// Revisión -// -// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y revisión -// mediante el carácter '*', como se muestra a continuación: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: NeutralResourcesLanguageAttribute("es-ES")] diff --git a/WindowsPhone/jsonrpc4net/jsonrpc4net/jsonrpc4net.csproj b/WindowsPhone/jsonrpc4net/jsonrpc4net/jsonrpc4net.csproj deleted file mode 100644 index da6734d..0000000 --- a/WindowsPhone/jsonrpc4net/jsonrpc4net/jsonrpc4net.csproj +++ /dev/null @@ -1,129 +0,0 @@ - - - - Debug - AnyCPU - 10.0.20506 - 2.0 - {9FC57CC3-23D0-486B-A3E4-92C547561949} - {C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - GumartinM.JsonRPC4Mono - jsonrpc4net - WindowsPhone - v8.0 - $(TargetFrameworkVersion) - false - true - 11.0 - true - en-US - - - true - full - false - Bin\Debug - DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - - - pdbonly - true - Bin\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - true - full - false - Bin\x86\Debug - DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - pdbonly - true - Bin\x86\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - true - full - false - Bin\ARM\Debug - DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - pdbonly - true - Bin\ARM\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - - - - - - - - ..\packages\Newtonsoft.Json.6.0.1\lib\portable-net45+wp80+win8\Newtonsoft.Json.dll - - - ..\packages\NLog.2.1.0\lib\sl4-windowsphone71\NLog.dll - - - ..\packages\Microsoft.Net.Http.2.2.18\lib\sl4-windowsphone71\System.Net.Http.dll - - - ..\packages\Microsoft.Net.Http.2.2.18\lib\sl4-windowsphone71\System.Net.Http.Extensions.dll - - - ..\packages\Microsoft.Net.Http.2.2.18\lib\sl4-windowsphone71\System.Net.Http.Primitives.dll - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/WindowsPhone/jsonrpc4net/jsonrpc4net/packages.config b/WindowsPhone/jsonrpc4net/jsonrpc4net/packages.config deleted file mode 100644 index e09220d..0000000 --- a/WindowsPhone/jsonrpc4net/jsonrpc4net/packages.config +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/jsonrpc4net/jsonrpc4net.Monodevelop.sln b/jsonrpc4net/jsonrpc4net.Monodevelop.sln new file mode 100644 index 0000000..eba6c90 --- /dev/null +++ b/jsonrpc4net/jsonrpc4net.Monodevelop.sln @@ -0,0 +1,21 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "jsonrpc4net", "jsonrpc4net\jsonrpc4net.Monodevelop.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 diff --git a/jsonrpc4net/jsonrpc4net.WindowsPhone8.sln b/jsonrpc4net/jsonrpc4net.WindowsPhone8.sln new file mode 100644 index 0000000..5b01a77 --- /dev/null +++ b/jsonrpc4net/jsonrpc4net.WindowsPhone8.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.30110.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "jsonrpc4net", "jsonrpc4net\jsonrpc4net.WindowsPhone8.csproj", "{9FC57CC3-23D0-486B-A3E4-92C547561949}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|ARM = Debug|ARM + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|ARM = Release|ARM + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|ARM.ActiveCfg = Debug|ARM + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|ARM.Build.0 = Debug|ARM + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|x86.ActiveCfg = Debug|x86 + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Debug|x86.Build.0 = Debug|x86 + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|Any CPU.Build.0 = Release|Any CPU + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|ARM.ActiveCfg = Release|ARM + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|ARM.Build.0 = Release|ARM + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|x86.ActiveCfg = Release|x86 + {9FC57CC3-23D0-486B-A3E4-92C547561949}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/jsonrpc4net/jsonrpc4net/ExceptionResolver.cs b/jsonrpc4net/jsonrpc4net/ExceptionResolver.cs new file mode 100644 index 0000000..4b302c5 --- /dev/null +++ b/jsonrpc4net/jsonrpc4net/ExceptionResolver.cs @@ -0,0 +1,65 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; + +namespace GumartinM.JsonRPC4NET +{ + public class ExceptionResolver + { + /// + /// Resolves the exception. + /// + /// The exception. + /// Error token. + public Exception ResolveException(JToken errorToken) + { + JObject errorData = (JObject)errorToken; + IDictionary 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 message = data.Value("message"); + + Exception endException = CreateException(exceptionTypeName, message); + + return endException; + } + + /// + /// Creates the json rpc client exception. + /// + /// The json rpc client exception. + /// Error token. + private JsonRpcClientException CreateJsonRpcClientException(JToken errorToken) + { + return new JsonRpcClientException( + errorToken.Value("code") ?? 0, + errorToken.Value("message"), + errorToken.SelectToken("data")); + } + + /// + /// Creates the exception. + /// + /// The exception. + /// Exception type name. + /// Message. + private Exception CreateException(string exceptionTypeName, string message) + { + return new Exception("Remote exception: " + exceptionTypeName + "Message: " + message); + } + } +} diff --git a/jsonrpc4net/jsonrpc4net/JsonRpcClientException.cs b/jsonrpc4net/jsonrpc4net/JsonRpcClientException.cs new file mode 100644 index 0000000..4adc5c1 --- /dev/null +++ b/jsonrpc4net/jsonrpc4net/JsonRpcClientException.cs @@ -0,0 +1,49 @@ +using Newtonsoft.Json.Linq; +using System; + +namespace GumartinM.JsonRPC4NET +{ + public class JsonRpcClientException : System.Exception + { + /// + /// The _code. + /// + private readonly int _code; + + /// + /// The _data. + /// + private readonly JToken _data; + + /// + /// Initializes a new instance of the class. + /// + /// Code. + /// Message. + /// Data. + public JsonRpcClientException(int code, String message, JToken data) + : base(message) + { + _code = code; + _data = data; + } + + /// + /// Gets the code. + /// + /// The code. + public int getCode() + { + return _code; + } + + /// + /// Gets the data. + /// + /// The data. + public JToken getData() + { + return _data; + } + } +} diff --git a/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs b/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs new file mode 100644 index 0000000..2eaf5f2 --- /dev/null +++ b/jsonrpc4net/jsonrpc4net/JsonRpcHttpAsyncClient.cs @@ -0,0 +1,155 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Serialization; +using NLog; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace GumartinM.JsonRPC4NET +{ + public class JsonRpcHttpAsyncClient + { + /// + /// RPC call id. + /// + private long _nextId; + + /// + /// The logger. + /// + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + /// + /// The _json settings. + /// + private readonly JsonSerializerSettings _jsonSettings = + new JsonSerializerSettings + { + Error = delegate(object sender, ErrorEventArgs args) + { + _logger.Error(args.ErrorContext.Error.Message); + args.ErrorContext.Handled = true; + } + }; + + /// + /// The _exception resolver. + /// + private readonly ExceptionResolver _exceptionResolver = new ExceptionResolver(); + + + + /// + /// Posts the remote service async. + /// + /// The remote service async. + /// URI. + /// Method. + /// The 1st type parameter. + async public Task PostRemoteServiceAsync(string uri, string method) + { + POSTResult postResult = await this.PostAsync(uri, method, CancellationToken.None); + + return postResult.result; + } + + /// + /// Posts the async. + /// + /// The async. + /// URI. + /// Method. + /// Cancellation. + /// The 1st type parameter. + async private Task> PostAsync(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(jsonBytes); + } + + throw new Exception("Unexpected response code: " + response.StatusCode); + } + } + + /// + /// Reads the response. + /// + /// The response. + /// Json bytes. + /// The 1st type parameter. + private POSTResult ReadResponse(byte[] jsonBytes) + { + string json = System.Text.Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length); + + JObject jsonObjects = JObject.Parse(json); + IDictionary jsonTokens = jsonObjects; + + + if (jsonTokens.ContainsKey("error")) + { + throw _exceptionResolver.ResolveException(jsonObjects["error"]); + } + + if (jsonTokens.ContainsKey("result")) + { + return JsonConvert.DeserializeObject>(json, _jsonSettings); + } + + throw new JsonRpcClientException(0, "There is not error nor result in JSON response data.", jsonObjects); + } + + /// + /// Send a POST request to the specified Uri as an asynchronous operation. + /// + /// The Uri the request is sent to. + /// The HTTP request content sent to the server. + /// Cancellation token. + /// When some error. + /// System.Threading.Tasks.Task]]>.The task object representing the asynchronous operation. + async private Task 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 + { + public string id { get; set; } + public string jsonrpc { get; set; } + public TResult result { get; set; } + } + } +} diff --git a/jsonrpc4net/jsonrpc4net/Properties/AssemblyInfo.cs b/jsonrpc4net/jsonrpc4net/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..992223a --- /dev/null +++ b/jsonrpc4net/jsonrpc4net/Properties/AssemblyInfo.cs @@ -0,0 +1,37 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Resources; + +// La información general de un ensamblado se controla mediante el siguiente +// conjunto de atributos. Cambie los valores de estos atributos para modificar la información +// asociada a un ensamblado. +[assembly: AssemblyTitle("jsonrpc4net")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("jsonrpc4net")] +[assembly: AssemblyCopyright("Copyright © 2014")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Si ComVisible se establece en False, los componentes COM no verán los +// tipos de este ensamblado. Si necesita obtener acceso a un tipo de este ensamblado desde +// COM, establezca el atributo ComVisible en True en este tipo. +[assembly: ComVisible(false)] + +// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM +[assembly: Guid("9fc57cc3-23d0-486b-a3e4-92c547561949")] + +// La información de versión de un ensamblado consta de los cuatro valores siguientes: +// +// Versión principal +// Versión secundaria +// Número de compilación +// Revisión +// +// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y revisión +// mediante el carácter '*', como se muestra a continuación: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: NeutralResourcesLanguageAttribute("es-ES")] diff --git a/jsonrpc4net/jsonrpc4net/jsonrpc4net.Monodevelop.csproj b/jsonrpc4net/jsonrpc4net/jsonrpc4net.Monodevelop.csproj new file mode 100644 index 0000000..37f655b --- /dev/null +++ b/jsonrpc4net/jsonrpc4net/jsonrpc4net.Monodevelop.csproj @@ -0,0 +1,53 @@ + + + + Debug + AnyCPU + 12.0.0 + 2.0 + {0C624E8F-9C80-457F-A7D1-39FA29E23F79} + Library + GumartinM.JsonRPC4NET + jsonrpc4net + v4.5 + Dirty implementation of JSON RPC. Just trying to learn how +to use C#. + + + true + full + false + bin\Debug + DEBUG; + prompt + 4 + false + + + full + true + bin\Release + prompt + 4 + false + + + + + ..\..\..\..\..\..\..\usr\mymono\lib\mono\4.5\System.Net.Http.dll + + + monodevelop + + + ..\..\ThirdParty\Libs\NLog\net45\NLog.dll + + + + + + + + + + \ No newline at end of file diff --git a/jsonrpc4net/jsonrpc4net/jsonrpc4net.WindowsPhone8.csproj b/jsonrpc4net/jsonrpc4net/jsonrpc4net.WindowsPhone8.csproj new file mode 100644 index 0000000..da6734d --- /dev/null +++ b/jsonrpc4net/jsonrpc4net/jsonrpc4net.WindowsPhone8.csproj @@ -0,0 +1,129 @@ + + + + Debug + AnyCPU + 10.0.20506 + 2.0 + {9FC57CC3-23D0-486B-A3E4-92C547561949} + {C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + GumartinM.JsonRPC4Mono + jsonrpc4net + WindowsPhone + v8.0 + $(TargetFrameworkVersion) + false + true + 11.0 + true + en-US + + + true + full + false + Bin\Debug + DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE + true + true + prompt + 4 + + + + + pdbonly + true + Bin\Release + TRACE;SILVERLIGHT;WINDOWS_PHONE + true + true + prompt + 4 + + + true + full + false + Bin\x86\Debug + DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE + true + true + prompt + 4 + + + pdbonly + true + Bin\x86\Release + TRACE;SILVERLIGHT;WINDOWS_PHONE + true + true + prompt + 4 + + + true + full + false + Bin\ARM\Debug + DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE + true + true + prompt + 4 + + + pdbonly + true + Bin\ARM\Release + TRACE;SILVERLIGHT;WINDOWS_PHONE + true + true + prompt + 4 + + + + + + + + + + ..\packages\Newtonsoft.Json.6.0.1\lib\portable-net45+wp80+win8\Newtonsoft.Json.dll + + + ..\packages\NLog.2.1.0\lib\sl4-windowsphone71\NLog.dll + + + ..\packages\Microsoft.Net.Http.2.2.18\lib\sl4-windowsphone71\System.Net.Http.dll + + + ..\packages\Microsoft.Net.Http.2.2.18\lib\sl4-windowsphone71\System.Net.Http.Extensions.dll + + + ..\packages\Microsoft.Net.Http.2.2.18\lib\sl4-windowsphone71\System.Net.Http.Primitives.dll + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jsonrpc4net/jsonrpc4net/packages.config b/jsonrpc4net/jsonrpc4net/packages.config new file mode 100644 index 0000000..e09220d --- /dev/null +++ b/jsonrpc4net/jsonrpc4net/packages.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file