Downloader.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using Avalonia.Controls.ApplicationLifetimes;
  2. using Avalonia.Threading;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Threading.Tasks;
  12. using VeloeMinecraftLauncher.ViewModels;
  13. using VeloeMinecraftLauncher.Views;
  14. namespace VeloeMinecraftLauncher.MinecraftLauncher
  15. {
  16. internal static class Downloader
  17. {
  18. public static T DownloadAndDeserializeJsonData<T>(string url) where T : new()
  19. {
  20. using (var webClient = new HttpClient())
  21. {
  22. var jsonData = string.Empty;
  23. try
  24. {
  25. Settings.logger.Debug($"Downloading: {url.Split('/').Last()}");
  26. jsonData = webClient.GetStringAsync(url).Result;
  27. }
  28. catch (Exception ex)
  29. {
  30. var message = ex.Message;
  31. var stackTrace = ex.StackTrace;
  32. Settings.logger.Error(ex.Message);
  33. Settings.logger.Error(ex.StackTrace);
  34. Exception innerException = ex.InnerException;
  35. while (innerException is not null)
  36. {
  37. message += "\n" + innerException.Message;
  38. stackTrace += "\n" + innerException.StackTrace;
  39. Settings.logger.Error(innerException.Message);
  40. Settings.logger.Error(innerException.StackTrace);
  41. innerException = innerException.InnerException;
  42. }
  43. Dispatcher.UIThread.InvokeAsync(() =>
  44. {
  45. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  46. {
  47. Dispatcher.UIThread.InvokeAsync(() =>
  48. {
  49. var ErrorMessageViewModel = new ErrorWindowViewModel(message, stackTrace);
  50. var ErrorMessage = new ErrorWindow()
  51. {
  52. DataContext = ErrorMessageViewModel
  53. };
  54. ErrorMessage.ShowDialog(desktop.MainWindow);
  55. });
  56. }
  57. });
  58. }
  59. if (string.IsNullOrEmpty(jsonData))
  60. {
  61. Settings.logger.Warning("Empty string!");
  62. return new T();
  63. }
  64. else
  65. {
  66. //Settings.logger.Debug("Return serialized string.");
  67. return JsonSerializer.Deserialize<T>(jsonData);
  68. }
  69. /*
  70. return string.IsNullOrEmpty(jsonData)
  71. ? new T()
  72. : JsonSerializer.Deserialize<T>(jsonData);*/
  73. }
  74. }
  75. public static void DownloadFile(string url, string path, string filename)
  76. {
  77. using (var webClient = new WebClient())
  78. {
  79. if (!Directory.Exists(path))
  80. Directory.CreateDirectory(path);
  81. webClient.DownloadFileAsync(new System.Uri(url), path + "/" + filename);
  82. }
  83. }
  84. }
  85. }