diff --git a/DetailedLogSwitcher/DetailedLogSwitcher.csproj b/DetailedLogSwitcher/DetailedLogSwitcher.csproj index f25e4ad..8812741 100644 --- a/DetailedLogSwitcher/DetailedLogSwitcher.csproj +++ b/DetailedLogSwitcher/DetailedLogSwitcher.csproj @@ -9,11 +9,11 @@ - AnyCPU + x64 - AnyCPU + x64 diff --git a/DetailedLogSwitcher/Helper.cs b/DetailedLogSwitcher/Helper.cs new file mode 100644 index 0000000..d76c77d --- /dev/null +++ b/DetailedLogSwitcher/Helper.cs @@ -0,0 +1,15 @@ +using static System.Console; + +namespace DetailedLogSwitcher +{ + public class Helper + { + internal static void Pause() => ReadKey(true); + + internal static void ShowError(string message) + { + WriteLine(message); + Pause(); + } + } +} \ No newline at end of file diff --git a/DetailedLogSwitcher/Json.cs b/DetailedLogSwitcher/Json.cs index f7eecbf..333d3cd 100644 --- a/DetailedLogSwitcher/Json.cs +++ b/DetailedLogSwitcher/Json.cs @@ -2,7 +2,7 @@ namespace DetailedLogSwitcher { - public class Config + public class GlobalSettings { [JsonProperty("clnMainGroup")] diff --git a/DetailedLogSwitcher/Logic/Search.cs b/DetailedLogSwitcher/Logic/Search.cs new file mode 100644 index 0000000..77a45bf --- /dev/null +++ b/DetailedLogSwitcher/Logic/Search.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using Microsoft.Win32; +using Newtonsoft.Json; +using static System.Console; +using static DetailedLogSwitcher.Result; + +namespace DetailedLogSwitcher +{ + public static class SearchConfigs + { + internal static Result SearchNLogs(out List nLogPaths) + { + WriteLine("Получение установленных программ...\n"); + + nLogPaths = new List(); + + using RegistryKey zlKey = Registry.CurrentUser.OpenSubKey(@"Software\ZennoLab"); + if (zlKey != null) + { + string[] langs = {"RU", "EN", "CN"}; + foreach (string lang in langs) + { + using RegistryKey langKey = zlKey.OpenSubKey(lang); + if(langKey == null) continue; + + string[] products = langKey.GetSubKeyNames(); + foreach (string product in products) + { + using RegistryKey productKey = langKey.OpenSubKey(product); + if(productKey == null) continue; + + string[] versions = productKey.GetSubKeyNames(); + foreach (string ver in versions) + { + using RegistryKey verKey = productKey.OpenSubKey(ver); + + if(verKey == null || (string)verKey.GetValue("SuccessInstall") != "True") continue; + + string productPath = (string)verKey.GetValue("InstallDir"); + if (!string.IsNullOrEmpty(productPath)) + { + string nLogPath = productPath + @"\Progs\NLog.config"; + if (File.Exists(nLogPath)) + { + nLogPaths.Add(nLogPath); + WriteLine(@"Найден NLog.config версии " + ver); + } + else + { + WriteLine($"Продукт {product} найден в реестре, но NLog.config не найден по пути: " + nLogPath); + continue; + } + } + else + { + WriteLine("Продукт найден в реестре, но InstallDir не установлен."); + continue; + } + } + } + } + } + else + { + return Error(@"Ни одна программа не установлена. Не найден: HKCU\Software\ZennoLab"); + } + + if (nLogPaths.Count == 0) + return Error("Ни один NLog.config не найден."); + + return Ok(nLogPaths); + } + + internal static Result SearchGlobalSettings(out List globalSettingsPaths) + { + WriteLine("\nПроверка наличия глобальных настроек...\n"); + + globalSettingsPaths = new List(); + + string appDataPath = Environment.GetEnvironmentVariable("APPDATA"); + + string[] versions = {"5", "7"}; + + foreach (string ver in versions) + { + string path = $@"{appDataPath}\ZennoLab\ZennoPoster\{ver}\Settings\globalsettings.settings.json"; + + if (File.Exists(path)) + { + globalSettingsPaths.Add(path); + WriteLine($@"Глобальный конфиг {ver} версии найден."); + } + } + + if (globalSettingsPaths.Count == 0) + return Error("Ни один из глобальных конфигов не найден!"); + + return Ok(globalSettingsPaths); + + #region + + // string zennoposterPath = Environment.GetEnvironmentVariable("ZennoPosterCurrentPath"); + // + // if(string.IsNullOrEmpty(zennoposterPath)) + // WriteLine("Переменная окружения ZennoPosterCurrentPath не установлена. Поиск путей по умолчанию..."); + // + // string[] zennolabPaths = {@"C:\Program Files\ZennoLab", @"C:\Program Files (x86)\ZennoLab"}; + // string[] langs = {"EN", "RU", /*"CN"*/}; + // + // foreach (string zlPath in zennolabPaths) + // { + // foreach (string lang in langs) + // { + // string path = $@"{zlPath}\{lang}"; + // } + // } + + #endregion + } + } +} \ No newline at end of file diff --git a/DetailedLogSwitcher/Logic/Setup.cs b/DetailedLogSwitcher/Logic/Setup.cs new file mode 100644 index 0000000..5f5c919 --- /dev/null +++ b/DetailedLogSwitcher/Logic/Setup.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Xml; +using System.Xml.XPath; +using Newtonsoft.Json; +using static System.Console; +using static DetailedLogSwitcher.NlogState; +using Formatting = Newtonsoft.Json.Formatting; + +namespace DetailedLogSwitcher +{ + public static class NlogState + { + public const string Trace = "Trace"; + public const string Debug = "Debug"; + } + + public static class Setup + { + public static void ConfigureGlobalSettings(List paths, bool newState) + { + foreach (string path in paths) + { + string json = File.ReadAllText(path); + GlobalSettings[] cfg = JsonConvert.DeserializeObject(json); + + foreach (GlobalSettings c in cfg) + { + if (c.ClnName == "DetailedLogEnabled" && c.ClnSubGroup == "Log") + { + string newStateStr = newState.ToString(); + + if (c.ClnValue == newStateStr) + { + WriteLine($"Подробный лог в глобальной настройке уже {(newState ? "включён" : "выключен")} по пути: " + path); + continue; + } + else + { + c.ClnValue = newStateStr; + WriteLine("Включён подробный лог в глобальных настройках по пути: " + path); + + string output = JsonConvert.SerializeObject(cfg, Formatting.Indented); + File.WriteAllText(path, output); + break; + } + } + } + } + } + + public static void ConfigureNLogs(List paths, string newState) + { + foreach (string path in paths) + { + XmlDocument doc = new XmlDocument {PreserveWhitespace = true}; + doc.Load(path); + XPathNavigator navigator = doc.CreateNavigator(); + + const string xPath = "a:nlog/a:rules/a:logger/@minlevel"; + + XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable); + manager.AddNamespace("a", "http://www.nlog-project.org/schemas/NLog.xsd"); + XPathExpression query = navigator.Compile(xPath); + query.SetContext(manager); + XPathNodeIterator nodes = navigator.Select(query); + + bool isEdited = false; + + if (nodes.Count != 0) + { + while (nodes.MoveNext()) + { + XPathNavigator nav = nodes.Current; + string val = nav.Value; + if(val == "Fatal") continue; + if (val != newState) + { + nav.SetValue(newState); + isEdited = true; + } + } + + if (isEdited) + { + var writer = XmlWriter.Create(path, new XmlWriterSettings() + { + Indent = false, + Encoding = Encoding.Default, + //NewLineOnAttributes = false, + CloseOutput = true, + CheckCharacters = true, + //NewLineHandling = NewLineHandling.None, + }); + using (writer) doc.Save(writer); + + WriteLine("Настроен NLog.config по пути: " + path); + } + else + { + WriteLine("NLog.config уже настроен по пути: " + path); + } + } + else + { + WriteLine($"Не были получены элементы NLog.config по пути: " + path); + continue; + } + } + } + } +} \ No newline at end of file diff --git a/DetailedLogSwitcher/Main.cs b/DetailedLogSwitcher/Main.cs new file mode 100644 index 0000000..47746e5 --- /dev/null +++ b/DetailedLogSwitcher/Main.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using Newtonsoft.Json; +using static System.Console; +using static DetailedLogSwitcher.Helper; +using static DetailedLogSwitcher.SearchConfigs; + +namespace DetailedLogSwitcher +{ + internal static class Program + { + private static void Main(string[] args) + { + try + { + Result gsResult = SearchGlobalSettings(out List globalSettingsPaths); + switch(gsResult) + { + case Error result: + ShowError(result.Message); + return; + } + + Result nLogsResult = SearchNLogs(out List existNLogs); + switch(nLogsResult) + { + case Error result: + ShowError(result.Message); + return; + } + + for (int i = 1;; i++) + { + WriteLine("\nУправление:\n1 - включить\n2 - выключить\nq - выйти"); + Write("\nВвод: "); + ConsoleKeyInfo keyInfo = ReadKey(); + WriteLine(); + + switch (keyInfo.Key) + { + case ConsoleKey.Q: + return; + case ConsoleKey.D1: // Включение + Setup.ConfigureGlobalSettings(globalSettingsPaths, true); + Setup.ConfigureNLogs(existNLogs, NlogState.Trace); + return; + case ConsoleKey.D2: // Выключение + Setup.ConfigureGlobalSettings(globalSettingsPaths, false); + Setup.ConfigureNLogs(existNLogs, NlogState.Debug); + return; + } + + if (i == 5) + { + WriteLine("\nМножественный неверный ввод. Завершение работы..."); + Thread.Sleep(2000); + return; + } + + Thread.Sleep(250); + } + } + catch (Exception e) + { + WriteLine(e); + } + finally + { + Pause(); + } + } + } +} \ No newline at end of file diff --git a/DetailedLogSwitcher/Program.cs b/DetailedLogSwitcher/Program.cs deleted file mode 100644 index 73ebba2..0000000 --- a/DetailedLogSwitcher/Program.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using Newtonsoft.Json; -using static System.Console; - -namespace DetailedLogSwitcher -{ - internal static class Program - { - private static void Pause() => ReadKey(true); - - private static void Configure(List paths, bool newState) - { - WriteLine("Установка значения..."); - foreach (var path in paths) - { - string json = File.ReadAllText(path); - Config[] cfg = JsonConvert.DeserializeObject(json); - - foreach (Config c in cfg) - { - if (c.ClnName == "DetailedLogEnabled" && c.ClnSubGroup == "Log") - { - string newStateStr = newState.ToString(); - - if (c.ClnValue == newStateStr) - { - WriteLine("Настройка уже включена."); - return; - } - else c.ClnValue = newStateStr; - } - } - - string output = JsonConvert.SerializeObject(cfg, Formatting.Indented); - File.WriteAllText(path, output); - } - WriteLine("Значение установлено."); - } - - private static void Main(string[] args) - { - try - { - WriteLine("Проверка наличия конфигов\n"); - - string appDataPath = Environment.GetEnvironmentVariable("APPDATA"); // Папка %APPDATA% - - string[] versions = {"5", "7"}; - - List existConfigs = new List(); - - foreach (string ver in versions) - { - string path = $@"{appDataPath}\ZennoLab\ZennoPoster\{ver}\Settings\globalsettings.settings.json"; - bool isExist = File.Exists(path); - - if (isExist) - { - existConfigs.Add(path); - WriteLine($@"Конфиг {ver} версии найден."); - } - } - - if (existConfigs.Count == 0) - { - WriteLine("Ни один из конфигов не найден!"); - Pause(); - return; - } - - for (int i = 1;; i++) - { - WriteLine("\nУправление:\n1 - включить\n2 - выключить\nq - выйти"); - Write("\nВвод: "); - ConsoleKeyInfo keyInfo = ReadKey(); - WriteLine(); - - if (keyInfo.Key == ConsoleKey.Q) return; - else if (keyInfo.Key == ConsoleKey.D1) - { - Configure(existConfigs, true); - break; - } - else if (keyInfo.Key == ConsoleKey.D2) - { - Configure(existConfigs, false); - break; - } - else if (i == 5) - { - WriteLine("\nМножественный неверный ввод. Завершение работы..."); - Thread.Sleep(2000); - return; - } - - Thread.Sleep(250); - } - } - catch (Exception e) - { - WriteLine(e); - } - finally - { - Pause(); - } - } - } -} \ No newline at end of file diff --git a/DetailedLogSwitcher/Result.cs b/DetailedLogSwitcher/Result.cs new file mode 100644 index 0000000..1c97b0f --- /dev/null +++ b/DetailedLogSwitcher/Result.cs @@ -0,0 +1,29 @@ +namespace DetailedLogSwitcher +{ + public class Result + { + public bool IsError { get; internal set; } + + public static Ok Ok(T value) => new Ok(value); + + public static Error Error(string message) => new Error(message); + } + + public class Ok : Result + { + public T Value { get; private set; } + + internal Ok(T value) : base() => Value = value; + } + + public class Error : Result + { + public string Message { get; private set; } + + internal Error(string message) : base() + { + IsError = true; + Message = message; + } + } +} \ No newline at end of file