Skip to content

Commit

Permalink
Add log and reformat style
Browse files Browse the repository at this point in the history
  • Loading branch information
fahminlb33 committed Mar 6, 2021
1 parent b6bddb4 commit c72d00e
Show file tree
Hide file tree
Showing 13 changed files with 170 additions and 100 deletions.
7 changes: 3 additions & 4 deletions src/KFlearning/Models/Project.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using KFlearning.Core.Extensions;
using System;
using KFlearning.Core.Extensions;
using KFlearning.TemplateProvider;
using Newtonsoft.Json;
using System;

namespace KFlearning.Models
{
Expand All @@ -15,8 +15,7 @@ public class Project

public DateTime LastOpenAt { get; set; }

[JsonIgnore]
public ITemplateProvider Template { get; set; }
[JsonIgnore] public ITemplateProvider Template { get; set; }

public override string ToString()
{
Expand Down
21 changes: 9 additions & 12 deletions src/KFlearning/Program.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,4 @@
// SOLUTION : KFlearning
// PROJECT : KFlearning
// FILENAME : Program.cs
// AUTHOR : Fahmi Noor Fiqri, Kodesiana.com
// WEBSITE : https://kodesiana.com
// REPO : https://github.com/Kodesiana or https://github.com/fahminlb33
//
// This file is part of KFlearning, see LICENSE.
// See this code in repository URL above!

using System;
using System;
using System.Threading;
using System.Windows.Forms;
using Castle.Core.Logging;
Expand All @@ -24,7 +14,9 @@ static class Program
{
private const int MutexTimeout = 1000;
private const string MutexName = "KFlearning.SingleInstanceGuard";

public static WindsorContainer Container = new WindsorContainer();
private static ILogger _logger;

/// <summary>
/// The main entry point for the application.
Expand All @@ -44,11 +36,13 @@ static void Main(string[] args)
// install services
NLog.GlobalDiagnosticsContext.Set("logDirectory", PathHelpers.GetLogPath());
Container.Install(new KFlearningModulesInstaller());
_logger = Container.Resolve<ILogger>();

// find vscode
var path = Container.Resolve<IPathManager>();
if (!path.IsVscodeInstalled)
{
_logger.Debug("Visual Studio Code not found");
MessageBox.Show(Resources.VscodeNotInstalled, Resources.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return;
Expand All @@ -57,18 +51,21 @@ static void Main(string[] args)
// find mingw
if (!path.IsKfMingwInstalled)
{
_logger.Debug("KF-MinGW not found");
MessageBox.Show(Resources.KfmingwNotInstalled, Resources.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return;
}

// enable TLS
_logger.Debug("Enabling TLS support");
ApiHelpers.EnableTls();

// app exit handler
Application.ApplicationExit += Application_ApplicationExit;

// bootstrapper
_logger.Debug("Bootstrapping application");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(Container.Resolve<KFlearningApplicationContext>());
Expand All @@ -86,7 +83,7 @@ private static void Application_ApplicationExit(object sender, EventArgs e)
}
catch (Exception ex)
{
Container.Resolve<ILogger>().Error("Cannot save persistence", ex);
_logger.Error("Cannot save persistence", ex);
}
finally
{
Expand Down
1 change: 0 additions & 1 deletion src/KFlearning/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
// See this code in repository URL above!

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
Expand Down
55 changes: 31 additions & 24 deletions src/KFlearning/Services/FlutterInstallService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ public class FlutterInstallService : IFlutterInstallService
public string FlutterVersion { get; private set; }
public string InstallPath { get; set; }

public FlutterInstallService(IFlutterGitClient flutterService, WebClient webClient, IPathManager pathManager, ILogger logger)
public FlutterInstallService(IFlutterGitClient flutterService, WebClient webClient, IPathManager pathManager,
ILogger logger)
{
InstallPath = pathManager.GetPath(PathKind.FlutterInstallDirectory);

Expand Down Expand Up @@ -79,11 +80,12 @@ public void PreparationStep()
}
catch (Exception ex)
{
_logger.Error("Can't check for Flutter version.", ex);
_logger.Error("Can't check for Flutter version, fallback to default", ex);
FlutterVersion = FlutterGitClient.DefaultFlutterVersion;
OnInstallReady(this, new FlutterInstallReadyEventArgs
{
Ready = false,
ErrorMessage = ex.Message
Ready = true,
ErrorMessage = "Menggunakan versi Flutter default."
});
}
});
Expand All @@ -108,7 +110,11 @@ private void ExecuteSteps()
_downloadPath = Path.GetTempFileName();
var uri = _flutterService.GetFlutterDownloadUri(FlutterVersion);
_logger.DebugFormat("Flutter download path {0}", _downloadPath);
_logger.DebugFormat("Flutter URI path {0}", uri);
_logger.Info("Start Flutter download");
_cancellationSource.Token.Register(() => _webClient.CancelAsync());
await _webClient.DownloadFileTaskAsync(new Uri(uri), _downloadPath);
// step 2 --- extract to installfolder
Expand All @@ -118,14 +124,15 @@ private void ExecuteSteps()
Status = "Memulai ekstraksi..."
});
if (IsProcessCancelled()) return;
_logger.Info("Start Flutter extraction");
_cancellationSource.Token.ThrowIfCancellationRequested();
using (var zip = new ZipFile(_downloadPath))
{
var totalEntries = zip.Entries.Count;
var processedEntry = 0;
foreach (var entry in zip) // non-parallelism, the lib doesn't support parallel
{
if (IsProcessCancelled()) return;
_cancellationSource.Token.ThrowIfCancellationRequested();
var path = Path.GetFullPath(Path.Combine(InstallPath, "../" + entry.FileName));
if (entry.IsDirectory)
Expand All @@ -143,7 +150,7 @@ private void ExecuteSteps()
Interlocked.Increment(ref processedEntry);
OnProgressChanged(this, new FlutterInstallProgressEventArgs
{
ProgressPercentage = (int)((double)processedEntry / totalEntries * 100),
ProgressPercentage = (int) ((double) processedEntry / totalEntries * 100),
Status = "Memindahkan direktori..."
});
}
Expand All @@ -156,44 +163,44 @@ private void ExecuteSteps()
Status = "Mengatur environment variable..."
});
if (IsProcessCancelled()) return;
_logger.Info("Start Flutter environment configuration");
_cancellationSource.Token.ThrowIfCancellationRequested();
var pathEnv = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User);
if (pathEnv?.Contains(@"flutter\bin") == false)
{
pathEnv += ";" + Path.Combine(InstallPath, @"bin");
pathEnv += ";" + Path.Combine(InstallPath, @"bin");
Environment.SetEnvironmentVariable("PATH", pathEnv, EnvironmentVariableTarget.User);
}
// --- all done!
_logger.Info("Flutter install sequence finished");
OnInstallFinished(this, new FlutterInstallFinishedEventArgs
{
ErrorMessage = "Instalasi selesai.",
Success = true
});
}
catch (Exception e)
catch (TaskCanceledException cancelledEx)
{
_logger.Info("Flutter install sequence cancelled.", cancelledEx);
OnInstallFinished(this, new FlutterInstallFinishedEventArgs
{
ErrorMessage = e.Message,
ErrorMessage = "Instalasi dibatalkan.",
Success = false
});
}
catch (Exception ex)
{
_logger.Error("Flutter install sequence failed", ex);
OnInstallFinished(this, new FlutterInstallFinishedEventArgs
{
ErrorMessage = ex.Message,
Success = false
});
}
});
}

private bool IsProcessCancelled()
{
if (!_cancellationSource.IsCancellationRequested) return false;
OnInstallFinished(this, new FlutterInstallFinishedEventArgs
{
ErrorMessage = "Instalasi dibatalkan.",
Success = false
});

return true;
}

#endregion

#region Event Handlers
Expand Down Expand Up @@ -246,4 +253,4 @@ public class FlutterInstallFinishedEventArgs : EventArgs
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
}
}
27 changes: 22 additions & 5 deletions src/KFlearning/Services/HistoryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ public HistoryService(IPersistanceStorage storage)

public void Add(Project project)
{
if (!RecordHistory) return;
if (!RecordHistory)
{
return;
}

_projects.RemoveAll(x => x.Path == project.Path);
_projects.Add(project);
Expand All @@ -41,7 +44,11 @@ public void Add(Project project)

public void Clear()
{
if (!RecordHistory) return;
if (!RecordHistory)
{
return;
}

_projects.Clear();
}

Expand All @@ -52,8 +59,15 @@ public IEnumerable<Project> GetAll()

private void EnsureSize()
{
if (!RecordHistory) return;
if (_projects.Count <= HistorySize) return;
if (!RecordHistory)
{
return;
}

if (_projects.Count <= HistorySize)
{
return;
}

_projects.RemoveRange(HistorySize - 1, _projects.Count - HistorySize);
}
Expand All @@ -68,7 +82,10 @@ private HistorySettings CreateDefaultSettings()
public void Load()
{
var settings = _storage.Retrieve<HistorySettings>(HistorySettingsName) ?? CreateDefaultSettings();
if (!settings.Recording) return;
if (!settings.Recording)
{
return;
}

_projects.Clear();
_projects.AddRange(settings.Projects);
Expand Down
4 changes: 2 additions & 2 deletions src/KFlearning/Services/HistorySettings.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using KFlearning.Models;
using System.Collections.Generic;
using System.Collections.Generic;
using KFlearning.Models;

namespace KFlearning.Services
{
Expand Down
19 changes: 14 additions & 5 deletions src/KFlearning/Services/KFlearningApplicationContext.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
using KFlearning.Views;
using System;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Castle.Core.Logging;
using KFlearning.Views;

namespace KFlearning.Services
{
public class KFlearningApplicationContext : ApplicationContext
{
private readonly ILogger _logger;
private readonly Form _mainForm;

public KFlearningApplicationContext(ITelemetryService telemetryService, StartupForm form)
public KFlearningApplicationContext(ITelemetryService telemetryService, StartupForm form, ILogger logger)
{
_mainForm = form;
_logger = logger;

_logger.Info("Sending telemetry");
Task.Run(() => telemetryService.Load());

_mainForm.HandleDestroyed += OnFormDestroy;
Expand All @@ -21,7 +25,12 @@ public KFlearningApplicationContext(ITelemetryService telemetryService, StartupF

private void OnFormDestroy(object sender, EventArgs e)
{
if (!(sender is Form form) || form.RecreatingHandle) return;
if (!(sender is Form form) || form.RecreatingHandle)
{
return;
}

_logger.Info("Form is being destroyed");
form.HandleDestroyed -= OnFormDestroy;
OnMainFormClosed(sender, e);
}
Expand All @@ -36,4 +45,4 @@ protected override void Dispose(bool disposing)
base.Dispose(disposing);
}
}
}
}
8 changes: 4 additions & 4 deletions src/KFlearning/Services/KFlearningModulesInstaller.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using Castle.MicroKernel.Registration;
using System.Net;
using Castle.Facilities.Logging;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Services.Logging.NLogIntegration;
using Castle.Windsor;
using KFlearning.TemplateProvider;
using KFlearning.Views;
using System.Net;
using Castle.Facilities.Logging;
using Castle.Services.Logging.NLogIntegration;

namespace KFlearning.Services
{
Expand Down
7 changes: 6 additions & 1 deletion src/KFlearning/Services/ProjectService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.IO;
using Castle.Core.Logging;
using KFlearning.Core.Extensions;
using KFlearning.Core.Services;
using KFlearning.Models;
Expand All @@ -24,13 +25,15 @@ public class ProjectService : IProjectService
private readonly IVisualStudioCodeService _visualStudioCodeService;
private readonly ITemplateService _template;
private readonly IPathManager _path;
private readonly ILogger _logger;

public ProjectService(IVisualStudioCodeService visualStudioCodeService, IPathManager path,
ITemplateService template)
ITemplateService template, ILogger logger)
{
_visualStudioCodeService = visualStudioCodeService;
_path = path;
_template = template;
_logger = logger;
}

public Project Load(string path)
Expand All @@ -40,6 +43,8 @@ public Project Load(string path)

metadata.Path = path;
metadata.LastOpenAt = DateTime.Now;

_logger.DebugFormat("Loading project from {0}", path);
Save(metadata);

return metadata;
Expand Down
Loading

0 comments on commit c72d00e

Please sign in to comment.