From 861b83cda27e54ebd1e8bc316b05a5c4497d51e7 Mon Sep 17 00:00:00 2001 From: Wizzy69 Date: Sun, 12 Jun 2022 10:22:43 +0300 Subject: [PATCH] Cleaned up code --- PluginManager/Config.cs | 31 +++---- PluginManager/Items/Command.cs | 5 +- PluginManager/Items/ConsoleCommandsHandler.cs | 6 +- PluginManager/Items/Spinner.cs | 62 ------------- PluginManager/Loaders/Loader.cs | 9 +- PluginManager/Loaders/PluginLoader.cs | 4 +- .../Others/Exceptions/APIException.cs | 91 ------------------- PluginManager/Others/Functions.cs | 20 ++-- 8 files changed, 37 insertions(+), 191 deletions(-) delete mode 100644 PluginManager/Items/Spinner.cs delete mode 100644 PluginManager/Others/Exceptions/APIException.cs diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs index 686fee4..48a4a1f 100644 --- a/PluginManager/Config.cs +++ b/PluginManager/Config.cs @@ -1,6 +1,5 @@ using PluginManager.Others; using System.IO; -using System.Linq; using System.Text.Json; using System.Threading.Tasks; using System.Collections.Generic; @@ -9,27 +8,27 @@ namespace PluginManager { internal class AppConfig { - public Dictionary ApplicationVariables { get; set; } - public List ProtectedKeyWords { get; set; } + public Dictionary? ApplicationVariables { get; set; } + public List? ProtectedKeyWords { get; set; } } public static class Config { - private static AppConfig appConfig; + private static AppConfig? appConfig { get; set; } public static bool AddValueToVariables(string key, T value, bool isProtected) { - if (appConfig.ApplicationVariables.ContainsKey(key)) return false; + if (appConfig!.ApplicationVariables!.ContainsKey(key)) return false; if (value == null) return false; appConfig.ApplicationVariables.Add(key, value); - if (isProtected) appConfig.ProtectedKeyWords.Add(key); + if (isProtected) appConfig.ProtectedKeyWords!.Add(key); SaveConfig(); return true; } public static T? GetValue(string key) { - if (!appConfig.ApplicationVariables.ContainsKey(key)) return default; + if (!appConfig!.ApplicationVariables!.ContainsKey(key)) return default; try { JsonElement element = (JsonElement)appConfig.ApplicationVariables[key]; @@ -43,8 +42,8 @@ namespace PluginManager public static bool SetValue(string key, T value) { - if (!appConfig.ApplicationVariables.ContainsKey(key)) return false; - if (appConfig.ProtectedKeyWords.Contains(key)) return false; + if (!appConfig!.ApplicationVariables!.ContainsKey(key)) return false; + if (appConfig.ProtectedKeyWords!.Contains(key)) return false; if (value == null) return false; appConfig.ApplicationVariables[key] = JsonSerializer.SerializeToElement(value); @@ -54,8 +53,8 @@ namespace PluginManager public static bool RemoveKey(string key) { - appConfig.ApplicationVariables.Remove(key); - appConfig.ProtectedKeyWords.Remove(key); + appConfig!.ApplicationVariables!.Remove(key); + appConfig.ProtectedKeyWords!.Remove(key); SaveConfig(); return true; } @@ -63,7 +62,7 @@ namespace PluginManager public static async void SaveConfig() { string path = Functions.dataFolder + "config.json"; - await Functions.SaveToJsonFile(path, appConfig); + await Functions.SaveToJsonFile(path, appConfig!); } public static async Task LoadConfig() @@ -72,15 +71,15 @@ namespace PluginManager if (File.Exists(path)) { appConfig = await Functions.ConvertFromJson(path); - Functions.WriteLogFile($"Loaded {appConfig.ApplicationVariables.Keys.Count} application variables.\nLoaded {appConfig.ProtectedKeyWords.Count} readonly variables."); + Functions.WriteLogFile($"Loaded {appConfig.ApplicationVariables!.Keys.Count} application variables.\nLoaded {appConfig.ProtectedKeyWords!.Count} readonly variables."); } else appConfig = new() { ApplicationVariables = new Dictionary(), ProtectedKeyWords = new List() }; } - public static bool ContainsValue(T value) => appConfig.ApplicationVariables.ContainsValue(value!); - public static bool ContainsKey(string key) => appConfig.ApplicationVariables.ContainsKey(key); + public static bool ContainsValue(T value) => appConfig!.ApplicationVariables!.ContainsValue(value!); + public static bool ContainsKey(string key) => appConfig!.ApplicationVariables!.ContainsKey(key); - public static Dictionary GetAllVariables() => new(appConfig.ApplicationVariables); + public static Dictionary GetAllVariables() => new(appConfig!.ApplicationVariables!); } } diff --git a/PluginManager/Items/Command.cs b/PluginManager/Items/Command.cs index 6850ece..12c67c3 100644 --- a/PluginManager/Items/Command.cs +++ b/PluginManager/Items/Command.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using Discord.WebSocket; using PluginManager.Others; @@ -41,4 +42,4 @@ internal class Command /// The prefix that is used for the command /// public char PrefixUsed { get; } -} +} \ No newline at end of file diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/PluginManager/Items/ConsoleCommandsHandler.cs index 5ac5947..0636030 100644 --- a/PluginManager/Items/ConsoleCommandsHandler.cs +++ b/PluginManager/Items/ConsoleCommandsHandler.cs @@ -23,7 +23,7 @@ public class ConsoleCommandsHandler { this.client = client; InitializeBasicCommands(); - Console.WriteLine("Initalized console command handeler !"); + Console.WriteLine("Initialized console command handler !"); } private void InitializeBasicCommands() @@ -55,7 +55,7 @@ public class ConsoleCommandsHandler AddCommand("lp", "Load plugins", () => { if (pluginsLoaded) return; - var loader = new PluginLoader(client); + var loader = new PluginLoader(client!); loader.onCMDLoad += (name, typeName, success, exception) => { Console.ForegroundColor = ConsoleColor.Green; @@ -237,7 +237,7 @@ public class ConsoleCommandsHandler data.Add(new[] { "-", "-" }); data.Add(new[] { "Key", "Value" }); data.Add(new[] { "-", "-" }); - foreach (var kvp in d) data.Add(new[] { kvp.Key, kvp.Value.ToString() }); + foreach (var kvp in d) data.Add(new string[] { kvp.Key, kvp.Value.ToString()! }); data.Add(new[] { "-", "-" }); Console_Utilities.FormatAndAlignTable(data); } diff --git a/PluginManager/Items/Spinner.cs b/PluginManager/Items/Spinner.cs deleted file mode 100644 index 910df5b..0000000 --- a/PluginManager/Items/Spinner.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Threading.Tasks; -using PluginManager.Others.Exceptions; - -namespace PluginManager.Items; - -public class Spinner -{ - /// - /// True if active, false otherwise - /// - public bool isSpinning; - - /// - /// The Spinner constructor - /// - public Spinner() - { - isSpinning = false; - } - - /// - /// The method that is called to start spinning the spinner - /// - public async void Start() - { - isSpinning = true; - var cnt = 0; - - while (isSpinning) - { - cnt++; - switch (cnt % 4) - { - case 0: - Console.Write("/"); - break; - case 1: - Console.Write("-"); - break; - case 2: - Console.Write("\\"); - break; - case 3: - Console.Write("|"); - break; - } - - Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); - await Task.Delay(250); - } - } - - /// - /// The method that is called to stop the spinner from spinning - /// - public void Stop() - { - if (!isSpinning) throw new APIException("Spinner was not spinning", GetType()); - isSpinning = false; - } -} diff --git a/PluginManager/Loaders/Loader.cs b/PluginManager/Loaders/Loader.cs index 1198eda..82aac6f 100644 --- a/PluginManager/Loaders/Loader.cs +++ b/PluginManager/Loaders/Loader.cs @@ -28,6 +28,11 @@ internal class Loader private string path { get; } private string extension { get; } + + internal delegate void FileLoadedEventHandler(LoaderArgs args); + + internal delegate void PluginLoadedEventHandler(LoaderArgs args); + internal event FileLoadedEventHandler? FileLoaded; internal event PluginLoadedEventHandler? PluginLoaded; @@ -100,8 +105,4 @@ internal class Loader return list; } - - internal delegate void FileLoadedEventHandler(LoaderArgs args); - - internal delegate void PluginLoadedEventHandler(LoaderArgs args); } diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index c848f7f..a4568d2 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -87,11 +87,11 @@ public class PluginLoader { if (e.IsLoaded) ((DBEvent)e.Plugin!).Start(_client); - if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception); + onEVELoad?.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception); } private void OnCommandLoaded(LoaderArgs e) { - if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception); + onCMDLoad?.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception); } } diff --git a/PluginManager/Others/Exceptions/APIException.cs b/PluginManager/Others/Exceptions/APIException.cs deleted file mode 100644 index 37264c1..0000000 --- a/PluginManager/Others/Exceptions/APIException.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; - -namespace PluginManager.Others.Exceptions; - -/// -/// Custom Exception for PluginManager -/// -[Serializable] -public class APIException : Exception -{ - /// - /// The APIException contructor - /// - /// The error message - /// The function where the message was triggered - /// The possible cause of the error - /// The error code - public APIException(string message, string? function, string possible_cause, Error error) : base(message) - { - ErrorCode = error; - Function = function; - PossibleCause = possible_cause; - } - - /// - /// The APIException contructor - /// - /// The error message - /// The function where the message was triggered - /// The error code - public APIException(string message, string? function, Error? errorCode) : base(message) - { - ErrorCode = errorCode; - Function = function; - } - - /// - /// The APIException contructor - /// - /// The error message - /// The function where the message was triggered - public APIException(string message, string? function) : base(message) - { - Function = function; - } - - /// - /// The APIException contructor - /// - /// The error message - public APIException(string message) : base(message) - { - } - - /// - /// The APIException constructor - /// - /// The error message - /// The class where the error was thrown - public APIException(string message, Type errorLocation) : base(message) - { - Function = errorLocation.FullName; - } - - /// - /// The function where the error occurred - /// - public string? Function { get; } = "not specified"; - - /// - /// The error code - /// - public Error? ErrorCode { get; } = Error.UNKNOWN_ERROR; - - /// - /// The possible cause that determined the error - /// - public string? PossibleCause { get; } = "not specified"; - - /// - /// Method to print the error to - /// - public void Print() - { - Console.WriteLine("Message Content: " + Message); - Console.WriteLine("Function: " + Function); - Console.WriteLine("Error Code: " + ErrorCode); - Console.WriteLine("Possible cause: " + PossibleCause); - if (StackTrace != null) Functions.WriteErrFile(StackTrace); - } -} diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index 0857eb1..0f3c5fc 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -32,15 +32,10 @@ namespace PluginManager.Others /// public static readonly string errFolder = @"./Output/Errors/"; - /// - /// The location for all languages - /// - public static readonly string langFolder = @"./Data/Languages/"; - /// /// Archives folder /// - public static readonly string pakFolder = @"./Data/Resources/PAKS/"; + public static readonly string pakFolder = @"./Data/Resources/PAK/"; /// @@ -49,13 +44,13 @@ namespace PluginManager.Others /// The file name that is inside the archive or its full path /// The archive location from the PAKs folder /// A string that represents the content of the file or null if the file does not exists or it has no content - public static async Task ReadFromPakAsync(string FileName, string archFile) + public static async Task ReadFromPakAsync(string FileName, string archFile) { archFile = pakFolder + archFile; Directory.CreateDirectory(pakFolder); if (!File.Exists(archFile)) throw new FileNotFoundException("Failed to load file !"); - string? textValue = null; + Stream? textValue = null; var fs = new FileStream(archFile, FileMode.Open); var zip = new ZipArchive(fs, ZipArchiveMode.Read); foreach (var entry in zip.Entries) @@ -64,7 +59,8 @@ namespace PluginManager.Others { Stream s = entry.Open(); StreamReader reader = new StreamReader(s); - textValue = await reader.ReadToEndAsync(); + textValue = reader.BaseStream; + textValue.Position = 0; reader.Close(); s.Close(); fs.Close(); @@ -239,7 +235,9 @@ namespace PluginManager.Others /// public static async Task SaveToJsonFile(string file, T Data) { - using (var s = File.OpenWrite(file)) await JsonSerializer.SerializeAsync(s, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true }); + var s = File.OpenWrite(file); + await JsonSerializer.SerializeAsync(s, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true }); + s.Close(); } /// @@ -259,7 +257,7 @@ namespace PluginManager.Others text.Position = 0; var obj = await JsonSerializer.DeserializeAsync(text); text.Close(); - return obj; + return (obj ?? default)!; } public static bool TryReadValueFromJson(string input, string codeName, out JsonElement element)