RemoteAgents Mono GTK implementation.
authorgu.martinm@gmail.com <gu.martinm@gmail.com>
Thu, 27 Feb 2014 01:26:03 +0000 (02:26 +0100)
committergu.martinm@gmail.com <gu.martinm@gmail.com>
Thu, 27 Feb 2014 01:26:03 +0000 (02:26 +0100)
Trying to use log4net
Nested using statements

Mono/RemoteAgents/GTKLinux/GTKLinux.csproj
Mono/RemoteAgents/GTKLinux/Log4Net.config [new file with mode: 0644]
Mono/RemoteAgents/GTKLinux/MainWindow.cs
Mono/RemoteAgents/GTKLinux/Model/CallRemoteProcedure.cs
Mono/RemoteAgents/GTKLinux/Properties/AssemblyInfo.cs
Mono/RemoteAgents/GTKLinux/View/View.cs
Mono/RemoteAgents/GTKLinux/ViewModel/ViewModel.cs

index 712fb3a..67b6699 100644 (file)
@@ -61,6 +61,9 @@ through JSON API.</Description>
       <Package>monodevelop</Package>
       <Private>True</Private>
     </Reference>
+    <Reference Include="log4net">
+      <HintPath>..\..\..\..\..\..\..\usr\mymono\custom\log4net-1.2.13\net\4.0\log4net.dll</HintPath>
+    </Reference>
   </ItemGroup>
   <ItemGroup>
     <EmbeddedResource Include="gtk-gui\gui.stetic">
@@ -85,4 +88,9 @@ through JSON API.</Description>
     <Folder Include="ViewModel\" />
     <Folder Include="View\" />
   </ItemGroup>
+  <ItemGroup>
+    <None Include="Log4Net.config">
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+    </None>
+  </ItemGroup>
 </Project>
\ No newline at end of file
diff --git a/Mono/RemoteAgents/GTKLinux/Log4Net.config b/Mono/RemoteAgents/GTKLinux/Log4Net.config
new file mode 100644 (file)
index 0000000..7c99490
--- /dev/null
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<log4net debug="true">
+       <!-- EasyConsoleAppender is set to be a ConsoleAppender -->
+    <appender name="EasyConsoleAppender" type="log4net.Appender.ConsoleAppender">
+        <layout type="log4net.Layout.PatternLayout">
+            <conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" />
+        </layout>
+    </appender>
+
+       <root>
+               <level value="INFO" />
+               <appender-ref ref="EasyConsoleAppender" />
+       </root>
+</log4net>
index 85a31d4..44acec5 100644 (file)
@@ -3,12 +3,15 @@ using Gtk;
 using System.Net.Http;
 using System.Threading.Tasks;
 using Example.RemoteAgents.GTKLinux.View;
+using log4net;
 
 namespace Example.RemoteAgents.GTKLinux
 {
     public partial class MainWindow: Gtk.Window
     {
         ViewImpl view;
+        private static readonly ILog logger = LogManager.GetLogger(
+            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
 
            public MainWindow () : base (Gtk.WindowType.Toplevel)
            {
@@ -35,7 +38,7 @@ namespace Example.RemoteAgents.GTKLinux
         async private void ButtonGetDateClicked(object sender, EventArgs a)
         {
             try {
-                string currentDate = await view.getCurrentDate();
+                string currentDate = await view.GetCurrentDateAsync();
                 if (currentDate != null)
                 {
                     this.RemoteDate.Buffer.Text = currentDate;
@@ -43,7 +46,7 @@ namespace Example.RemoteAgents.GTKLinux
             }
             catch (Exception e)
             {
-                Console.WriteLine("ButtonGetDateClicked. Message: {0}  Stacktrace: {1}", e.Message, e.StackTrace);
+                logger.Error("ButtonGetDateClicked error: ", e);
             }
         }
     }
index 548ea92..f444c0d 100644 (file)
@@ -10,13 +10,24 @@ 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> callRemoteService<TResult>(string uri, string method)
+    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";
@@ -25,34 +36,46 @@ namespace Example.RemoteAgents.GTKLinux.Model
       var jsonSettings = new JsonSerializerSettings{
         Error = delegate(object sender, ErrorEventArgs args)
         {
-          Console.WriteLine(args.ErrorContext.Error.Message);
+          logger.Error(args.ErrorContext.Error.Message);
           args.ErrorContext.Handled = true;
         }
       };
 
       string data = JsonConvert.SerializeObject(postData, jsonSettings);
-      HttpContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json-rpc");
 
-      HttpResponseMessage response = await this.issueCall(uri, content);
+      // 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>();
 
-      TResult result = default(TResult);
+        if (response.StatusCode == HttpStatusCode.OK) {
+          byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
+          string responseString = System.Text.Encoding.UTF8.GetString(responseBytes);
 
-      if (response.StatusCode == HttpStatusCode.OK) {
-        Task<byte[]> responseBytes = response.Content.ReadAsByteArrayAsync();
-        string responseString = System.Text.Encoding.UTF8.GetString(responseBytes.Result);
+          postResult = JsonConvert.DeserializeObject<POSTResult<TResult>>(responseString, jsonSettings);
+        }
 
-        POSTResult<TResult> postResult = JsonConvert.DeserializeObject<POSTResult<TResult>>(responseString, jsonSettings);
-        result = postResult.result;
+        return postResult;
       }
-
-      return result;
     }
 
-    async private Task<HttpResponseMessage> issueCall(string uri, HttpContent content)
+    /// <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);
+            return await client.PostAsync(uri, content, cancellation);
         }
     }
 
index 7b2678f..9d9a201 100644 (file)
@@ -19,4 +19,4 @@ using System.Runtime.CompilerServices;
 // 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)]
index f35dc80..93660f2 100644 (file)
@@ -9,9 +9,9 @@ namespace Example.RemoteAgents.GTKLinux.View
   {
     private static readonly ViewModelImpl vm = new ViewModelImpl();
 
-    async public Task<string> getCurrentDate()
+    async public Task<string> GetCurrentDateAsync()
     {
-      return await vm.getCurrentDate();
+      return await vm.GetCurrentDateAsync();
     }
   }
 }
index cae493a..e21730c 100644 (file)
@@ -7,11 +7,11 @@ namespace Example.RemoteAgents.GTKLinux.ViewModel
   public class ViewModelImpl
   {
     private static readonly string uri = "http://gumartinm.name/spring-mainapp/CurrentDateService.json";
-    private static readonly CallRemoteProcedure remoteProcedure = new CallRemoteProcedure();
+    private readonly CallRemoteProcedure remoteProcedure = new CallRemoteProcedure();
 
-    async public Task<string> getCurrentDate()
+    async public Task<string> GetCurrentDateAsync()
     {
-      return await remoteProcedure.callRemoteService<string>(uri, "getCurrentDate");
+      return await remoteProcedure.PostRemoteServiceAsync<string>(uri, "getCurrentDate");
     }
   }
 }