using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Threading; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using VeloeMinecraftLauncher.ViewModels; using VeloeMinecraftLauncher.Views; namespace VeloeMinecraftLauncher.MinecraftLauncher { internal static class Downloader { public static T DownloadAndDeserializeJsonData(string url) where T : new() { using (var webClient = new HttpClient()) { var jsonData = string.Empty; try { Settings.logger.Debug($"Downloading: {url.Split('/').Last()}"); jsonData = webClient.GetStringAsync(url).Result; } catch (Exception ex) { var message = ex.Message; var stackTrace = ex.StackTrace; Settings.logger.Error(ex.Message); Settings.logger.Error(ex.StackTrace); Exception innerException = ex.InnerException; while (innerException is not null) { message += "\n" + innerException.Message; stackTrace += "\n" + innerException.StackTrace; Settings.logger.Error(innerException.Message); Settings.logger.Error(innerException.StackTrace); innerException = innerException.InnerException; } Dispatcher.UIThread.InvokeAsync(() => { if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { Dispatcher.UIThread.InvokeAsync(() => { var ErrorMessageViewModel = new ErrorWindowViewModel(message, stackTrace); var ErrorMessage = new ErrorWindow() { DataContext = ErrorMessageViewModel }; ErrorMessage.ShowDialog(desktop.MainWindow); }); } }); } if (string.IsNullOrEmpty(jsonData)) { Settings.logger.Warning("Empty string!"); return new T(); } else { //Settings.logger.Debug("Return serialized string."); return JsonSerializer.Deserialize(jsonData); } /* return string.IsNullOrEmpty(jsonData) ? new T() : JsonSerializer.Deserialize(jsonData);*/ } } public static void DownloadFile(string url, string path, string filename) { using (var webClient = new WebClient()) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); webClient.DownloadFileAsync(new System.Uri(url), path + "/" + filename); } } } }