Skip to content

Commit

Permalink
Update service exception bubbling
Browse files Browse the repository at this point in the history
  • Loading branch information
fahminlb33 committed Mar 6, 2021
1 parent 484ca16 commit b6bddb4
Show file tree
Hide file tree
Showing 11 changed files with 161 additions and 163 deletions.
36 changes: 15 additions & 21 deletions src/KFlearning.Core/API/FlutterGitClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
Expand All @@ -19,6 +18,8 @@ public interface IFlutterGitClient

public class FlutterGitClient : IFlutterGitClient
{
public const string DefaultFlutterVersion = "1.22.6";

private static readonly HttpClient Client;

static FlutterGitClient()
Expand All @@ -32,28 +33,21 @@ static FlutterGitClient()

public async Task<string> GetLatestFlutterVersion()
{
try
{
var response = await Client.GetAsync("https://api.github.com/repos/flutter/flutter/git/refs/tags");
response.EnsureSuccessStatusCode();
var response = await Client.GetAsync("https://api.github.com/repos/flutter/flutter/git/refs/tags");
response.EnsureSuccessStatusCode();

var serializer = new JsonSerializer();
using (var bodyReader = new StreamReader(await response.Content.ReadAsStreamAsync(), Encoding.UTF8))
using (var jsonReader = new JsonTextReader(bodyReader))
var serializer = new JsonSerializer();
using (var bodyReader = new StreamReader(await response.Content.ReadAsStreamAsync(), Encoding.UTF8))
using (var jsonReader = new JsonTextReader(bodyReader))
{
var tags = serializer.Deserialize<List<FlutterGitTag>>(jsonReader);
var latest = tags?.LastOrDefault(x => !x.Ref.Contains("pre"));
if (latest == null)
{
var tags = serializer.Deserialize<List<FlutterGitTag>>(jsonReader);
var latest = tags?.LastOrDefault(x => !x.Ref.Contains("pre"));
if (latest == null)
{
throw new KFlearningException("Tidak dapat menemukan versi Flutter! Silakan download manual.");
}

return GetVersionFromTag(latest.Ref);
throw new KFlearningException("Tidak dapat menemukan versi Flutter! Silakan download manual.");
}
}
catch (Exception)
{
return "1.22.6";

return GetVersionFromTag(latest.Ref);
}
}

Expand All @@ -67,7 +61,7 @@ private string GetVersionFromTag(string tag)
return tag.Split('/').Last();
}

public partial class FlutterGitTag
public class FlutterGitTag
{
[JsonProperty("ref")]
public string Ref { get; set; }
Expand Down
21 changes: 18 additions & 3 deletions src/KFlearning.Core/Native/NativeConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,26 @@
{
internal static class NativeConstants
{
public const string UacRegistryKey = @"Software\Microsoft\Windows\CurrentVersion\Policies\System";
public const string UacRegistryValue = "EnableLUA";

public static uint STANDARD_RIGHTS_READ = 0x00020000;
public static uint TOKEN_QUERY = 0x0008;
public static uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY;

public const string UacRegistryKey = @"Software\Microsoft\Windows\CurrentVersion\Policies\System";
public const string UacRegistryValue = "EnableLUA";

public const string SystemPoliciesKey = @"Software\Microsoft\Windows\CurrentVersion\Policies\System";
public const string ActiveDesktopKey = @"Software\Microsoft\Windows\CurrentVersion\Policies\ActiveDesktop";
public const string ExplorerKey = @"Software\Microsoft\Windows\Current Version\Policies\Explorer";
public const string StoragePoliciesKey = @"SYSTEM\Current Control Set\Control\StorageDevicePolicies";
public const string DesktopKey = @"Control Panel\Desktop";

public const string NoChangingWallPaper = "NoChangingWallPaper";
public const string Wallpaper = "Wallpaper";
public const string WallpaperStyle = "WallpaperStyle";
public const string NoDispCPL = "NoDispCPL";
public const string DisableRegistryTools = "DisableRegistryTools";
public const string DisableTaskMgr = "DisableTaskMgr";
public const string WriteProtect = "WriteProtect";
public const string NoControlPanel = "NoControlPanel";
}
}
12 changes: 8 additions & 4 deletions src/KFlearning.Core/Remoting/KFServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@ public class KFServer : IKFServer
private const string KFserverProcessName = "kfserver";

private readonly IPathManager _pathManager;

public bool IsRunning => Process.GetProcessesByName(KFserverProcessName).Length > 0;


public KFServer(IPathManager pathManager)
{
_pathManager = pathManager;
Expand All @@ -41,6 +40,7 @@ public void Start(string servePath)
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
};

Process.Start(startInfo);
}

Expand All @@ -51,7 +51,7 @@ public void Stop()
foreach (var process in Process.GetProcessesByName(KFserverProcessName))
{
process.Kill();
process?.Dispose();
process.Dispose();
}
}
catch (Exception)
Expand All @@ -63,12 +63,16 @@ public void Stop()
public ServerInfo GetInfo()
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
throw new KFlearningException("Komputer ini tidak terhubung ke jaringan.");
}

var hosts = Dns.GetHostEntry(Dns.GetHostName());
var address = hosts.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);
if (address == null)
{
throw new KFlearningException("Tidak dapat menemukan IP komputer.");
}

return new ServerInfo
{
Expand All @@ -92,7 +96,7 @@ protected virtual void Dispose(bool disposing)

public void Dispose()
{
Dispose(disposing: true);
Dispose(true);
GC.SuppressFinalize(this);
}

Expand Down
1 change: 1 addition & 0 deletions src/KFlearning.Core/Remoting/RemoteShutdownServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ private void ReceiveCallback(IAsyncResult ar)
private void ProcessMessage(string message, IPAddress server)
{
if (!message.StartsWith(MessageShutdown)) return;

var cluster = message.Split('|')[1];
ShutdownRequested?.Invoke(this, new ShutdownRequestedEventArgs { Address = server, Clusster = cluster });
}
Expand Down
3 changes: 0 additions & 3 deletions src/KFlearning.Core/Services/PathManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace KFlearning.Core.Services
Expand Down Expand Up @@ -33,9 +32,7 @@ private enum PathName
#region Properies

public bool IsVscodeInstalled => _cachedPaths.ContainsKey(PathName.Vscode);

public bool IsKfMingwInstalled => _cachedPaths.ContainsKey(PathName.KFmingw);

public bool IsFlutterInstalled => _cachedPaths.ContainsKey(PathName.Flutter);

#endregion
Expand Down
22 changes: 11 additions & 11 deletions src/KFlearning.Core/Services/ProcessManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,33 +22,33 @@ public bool IsProcessElevated()
{
if (!IsUacEnabled())
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
bool result = principal.IsInRole(WindowsBuiltInRole.Administrator)
|| principal.IsInRole(0x200); //Domain Administrator
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
var result = principal.IsInRole(WindowsBuiltInRole.Administrator)
|| principal.IsInRole(0x200); //Domain Administrator
return result;
}

if (!NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle, NativeConstants.TOKEN_READ,
out TokenSafeHandle tokenHandle))
out var tokenHandle))
{
throw new Win32Exception();
}

using (tokenHandle)
{
int elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(typeof(TOKEN_ELEVATION_TYPE)));
IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
var elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(typeof(TOKEN_ELEVATION_TYPE)));
var elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);

try
{
bool success = NativeMethods.GetTokenInformation(tokenHandle,
var success = NativeMethods.GetTokenInformation(tokenHandle,
TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint) elevationResultSize,
out uint _);
out _);
if (success)
{
var elevationResult = (TOKEN_ELEVATION_TYPE) Marshal.ReadInt32(elevationTypePtr);
bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
var isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
return isProcessAdmin;
}
else
Expand All @@ -66,7 +66,7 @@ public bool IsProcessElevated()

public bool IsUacEnabled()
{
using (RegistryKey uacKey = Registry.LocalMachine.OpenSubKey(NativeConstants.UacRegistryKey, false))
using (var uacKey = Registry.LocalMachine.OpenSubKey(NativeConstants.UacRegistryKey, false))
{
return uacKey != null && uacKey.GetValue(NativeConstants.UacRegistryValue).Equals(1);
}
Expand Down
3 changes: 3 additions & 0 deletions src/KFlearning.Core/Services/ProcessWatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public interface IProcessWatcher
public class ProcessWatcher : IProcessWatcher
{
private const double PollingInterval = 5 * 60 * 1000;

private readonly object _lock = new object();
private readonly Timer _timer;
private DateTime _lastCheck;
Expand All @@ -33,6 +34,7 @@ public ProcessWatcher()
public void Start()
{
if (_timer.Enabled) return;

TotalSeconds = 0;
_lastCheck = DateTime.Now;
_timer.Start();
Expand All @@ -41,6 +43,7 @@ public void Start()
public void Stop()
{
if (!_timer.Enabled) return;

_timer_Elapsed(null, null);
_timer.Stop();
}
Expand Down
61 changes: 27 additions & 34 deletions src/KFlearning.Core/Services/SystemInfoService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,47 +31,40 @@ public class SystemInfoService : ISystemInfoService

public void Query()
{
try
{
if (_isLoaded) return;

// build device ID
string deviceId = "";

// OS info
var queryObj = SearchWmi("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem");
OS = queryObj["Caption"].ToString();
OSVersion = queryObj["Version"].ToString();
Architecture = queryObj["OSArchitecture"].ToString();
RAM = Convert.ToDouble(queryObj["TotalVisibleMemorySize"].ToString());
deviceId = queryObj["TotalVisibleMemorySize"].ToString();
if (_isLoaded) return;

// CPU info
queryObj = SearchWmi("root\\CIMV2", "SELECT * FROM Win32_Processor");
CPU = queryObj["Name"].ToString();
deviceId += queryObj["ProcessorId"].ToString();
// build device ID
string deviceId = "";

// Logical disk
queryObj = SearchWmi("root\\CIMV2", "SELECT * FROM Win32_LogicalDisk");
deviceId += queryObj["VolumeSerialNumber"].ToString();
// OS info
var queryObj = SearchWmi("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem");
OS = queryObj["Caption"].ToString();
OSVersion = queryObj["Version"].ToString();
Architecture = queryObj["OSArchitecture"].ToString();
RAM = Convert.ToDouble(queryObj["TotalVisibleMemorySize"].ToString());
deviceId = queryObj["TotalVisibleMemorySize"].ToString();

// hash the info
using (var hasher = new SHA256CryptoServiceProvider())
{
var bytes = Encoding.UTF8.GetBytes(deviceId);
var hashed = hasher.ComputeHash(bytes);
var hex = new StringBuilder(hashed.Length * 2);
// CPU info
queryObj = SearchWmi("root\\CIMV2", "SELECT * FROM Win32_Processor");
CPU = queryObj["Name"].ToString();
deviceId += queryObj["ProcessorId"].ToString();

foreach (byte b in hashed) hex.AppendFormat("{0:x2}", b);
DeviceId = hex.ToString();
}
// Logical disk
queryObj = SearchWmi("root\\CIMV2", "SELECT * FROM Win32_LogicalDisk");
deviceId += queryObj["VolumeSerialNumber"].ToString();

_isLoaded = true;
}
catch (Exception)
// hash the info
using (var hasher = new SHA256CryptoServiceProvider())
{
// ignore
var bytes = Encoding.UTF8.GetBytes(deviceId);
var hashed = hasher.ComputeHash(bytes);
var hex = new StringBuilder(hashed.Length * 2);

foreach (byte b in hashed) hex.AppendFormat("{0:x2}", b);
DeviceId = hex.ToString();
}

_isLoaded = true;
}

private ManagementBaseObject SearchWmi(string scope, string query)
Expand Down
Loading

0 comments on commit b6bddb4

Please sign in to comment.