VersionLogProcedure.cs 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace AwInitilizer.Procedure
  11. {
  12. public class VersionLogProcedure : ProcedureBase
  13. {
  14. public VersionLogProcedure() : base()
  15. {
  16. Name = "Version Logger";
  17. Content = "Report version back to MES";
  18. }
  19. internal override async Task<bool> Run()
  20. {
  21. var versionPair = await GetVersion();
  22. if (versionPair != null)
  23. {
  24. foreach (var infoPair in versionPair)
  25. {
  26. LogPair.Add(infoPair.Key, infoPair.Value);
  27. }
  28. return true;
  29. }
  30. else
  31. {
  32. return false;
  33. }
  34. }
  35. internal async Task<Dictionary<string, string>> GetVersion()
  36. {
  37. try
  38. {
  39. using (WebClient webClient = new WebClient())
  40. {
  41. NameValueCollection parameters = new NameValueCollection();
  42. parameters.Add("opt", "1");
  43. webClient.QueryString = parameters;
  44. using (Stream stream = await webClient.OpenReadTaskAsync($"https://{ServerIpAddress}/get_query_action.php"))
  45. // 使用 StreamReader 讀取 stream 內的字元
  46. using (StreamReader reader = new StreamReader(stream))
  47. {
  48. // 將 StreamReader 所讀到的字元轉為 string
  49. string request = reader.ReadToEnd();
  50. InfoLog += $"get version response:{request}\n";
  51. var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(request);
  52. var toReturn = new Dictionary<string, string>();
  53. foreach (var pair in values)
  54. {
  55. if (pair.Value is string v)
  56. {
  57. toReturn.Add(pair.Key, v);
  58. }
  59. else if (pair.Value is Newtonsoft.Json.Linq.JArray a)
  60. {
  61. try
  62. {
  63. var versionList = JsonConvert.DeserializeObject<List<string>>(a.ToString());
  64. for (int index = 0; index < versionList.Count; index++)
  65. {
  66. toReturn.Add(string.Format("{0}{1}", pair.Key, index), versionList[index]);
  67. }
  68. }
  69. catch
  70. {
  71. }
  72. }
  73. }
  74. return toReturn;
  75. }
  76. }
  77. }
  78. catch (Exception e)
  79. {
  80. Logger.Print("Get Version Failed", isError: true);
  81. Logger.Print(e.Message + "", isError: true);
  82. InfoLog += "Get Version Failed\n";
  83. InfoLog += e.Message;
  84. InfoLog += "\n";
  85. return null;
  86. }
  87. }
  88. }
  89. }