/// <summary> /// Convienance method for logging and printing errors and warnings found in a <see cref="ValidationResult" />. /// </summary> /// <param name="plugin"></param> /// <param name="validationResult"></param> public static void LogPrint(this TerrariaPlugin plugin, ValidationResult validationResult) { var traceLevel = TraceLevel.Info; var endPart = "."; int warnings = 0; int errors = 0; validationResult.GetTotals(ref errors, ref warnings); if (warnings == 0 && errors == 0) { return; } if (warnings > 0) { traceLevel = TraceLevel.Warning; } if (errors > 0) { traceLevel = TraceLevel.Error; } if (validationResult.Source != null) { endPart = $" in {validationResult.Source.ToString()}."; } plugin.LogPrint($"Found {errors} Errors, {warnings} Warnings{endPart}", traceLevel); RecurseLogPrintValidationResult(plugin, validationResult); }
private static void RecurseLogPrintValidationResult(TerrariaPlugin plugin, ValidationResult validationResult) { foreach (var err in validationResult.Errors) { plugin.LogPrint(err.ToString(), TraceLevel.Error); } foreach (var warn in validationResult.Warnings) { plugin.LogPrint(warn.ToString(), TraceLevel.Warning); } foreach (var ch in validationResult.Children) { RecurseLogPrintValidationResult(plugin, ch); } }
/// <summary> /// Attempts to load a json configuration saved at the specified path. If none exists, one will be created. Also checks for configuration errors, by /// calling JsonConfig.Validate(). /// </summary> /// <typeparam name="TConfig">JsonConfig subclass.</typeparam> /// <param name="plugin">TerrariaPlugin that houses the JsonConfig.</param> /// <param name="filePath">File path at which the config should resided.</param> /// <returns></returns> public static TConfig LoadOrCreate <TConfig>(TerrariaPlugin plugin, string filePath) where TConfig : JsonConfig, new() { TConfig config = default(TConfig); try { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); if (File.Exists(filePath)) { ServerApi.LogWriter.PluginWriteLine(plugin, $"Loading config from {filePath} ...", TraceLevel.Info); var json = File.ReadAllText(filePath); config = JsonConvert.DeserializeObject <TConfig>(json); } else { ServerApi.LogWriter.PluginWriteLine(plugin, $"Creating config at {filePath} ...", TraceLevel.Info); config = new TConfig(); Save(plugin, config, filePath); } int errors = 0, warnings = 0; var validationResult = config.Validate(); validationResult.Source = $"config file {filePath}."; validationResult.GetTotals(ref errors, ref warnings); if (errors > 0 || warnings > 0) { plugin.LogPrint(validationResult); } } catch (Exception ex) { ServerApi.LogWriter.PluginWriteLine(plugin, ex.Message, TraceLevel.Error); } return(config); }