MainWindow.xaml.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. using JsonRpcLite.Network;
  2. using JsonRpcLite.Rpc;
  3. using JsonRpcLite.Services;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Windows;
  15. using System.Windows.Controls;
  16. using System.Windows.Data;
  17. using System.Windows.Documents;
  18. using System.Windows.Input;
  19. using System.Windows.Media;
  20. using System.Windows.Media.Imaging;
  21. using System.Windows.Navigation;
  22. using System.Windows.Shapes;
  23. using WingInterfaceLibrary.Interface;
  24. using Path = System.IO.Path;
  25. namespace vStationManagementTool
  26. {
  27. public class RootObject
  28. {
  29. public Common common { get; set; }
  30. public Server server { get; set; }
  31. public List<string> flyinsonoServers { get; set; }
  32. }
  33. public class Common
  34. {
  35. public string dateTimeFormat { get; set; }
  36. }
  37. public class Server
  38. {
  39. public string current { get; set; }
  40. public List<string> optionSource { get; set; }
  41. }
  42. /// <summary>
  43. /// Interaction logic for MainWindow.xaml
  44. /// </summary>
  45. public partial class MainWindow : Window
  46. {
  47. private string _validationError;
  48. private string _configurePath = Path.Combine("..//",
  49. "URMWorkStation", "AppStorage", "config.conf");
  50. private string _serverStartPath = Path.Combine("..//", "FlyinsonoLabServer", "start - 1.bat");
  51. private string _serverClosePath = Path.Combine("..//", "FlyinsonoLabServer", "close - 1.bat");
  52. private string _pathApp = Path.Combine("..//", "URMWorkStation");
  53. private string _appStorage = Path.Combine("..//", "URMWorkStation", "AppStorage");
  54. private string _pathServer = Path.Combine("..//", "FlyinsonoLabServer");
  55. private string _versionPath= Path.Combine("..//", "StationVersion.txt");
  56. private RootObject _root;
  57. private bool _connectStatus;
  58. private bool _isTestingServer;
  59. private bool _hasServer;
  60. public MainWindow()
  61. {
  62. InitializeComponent();
  63. Init();
  64. }
  65. private void Init()
  66. {
  67. var hasServer = Directory.Exists(_pathServer);
  68. _hasServer = hasServer;
  69. var isSingle = false;
  70. try
  71. {
  72. var version=File.ReadAllText(_versionPath);
  73. isSingle = version.Trim().ToLower()=="single";
  74. }
  75. catch (Exception ex)
  76. {
  77. isSingle = _hasServer;
  78. }
  79. if (isSingle)
  80. {
  81. ServerArea.Visibility = Visibility.Visible;
  82. ClientArea.Visibility = Visibility.Collapsed;
  83. }
  84. else
  85. {
  86. ClientArea.Visibility = Visibility.Visible;
  87. ServerArea.Visibility = Visibility.Collapsed;
  88. }
  89. if (isSingle)
  90. {
  91. GetLocalIPAddress();
  92. GetServerState();
  93. }
  94. else {
  95. try
  96. {
  97. if (File.Exists(_configurePath))
  98. {
  99. var data = File.ReadAllText(_configurePath);
  100. _root = JsonConvert.DeserializeObject<RootObject>(data);
  101. ipAddress.Text = _root.server.current.Split(':')[1].Substring(2);
  102. portNum.Text = _root.server.current.Split(':')[2];
  103. }
  104. else {
  105. ipAddress.Text = "127.0.0.1";
  106. portNum.Text = "8303";
  107. if (_root == null)
  108. {
  109. _root = new RootObject();
  110. _root.flyinsonoServers = new List<string>();
  111. _root.flyinsonoServers.Add("https://bj.flyinsono.com");
  112. _root.common = new Common();
  113. _root.server = new Server();
  114. _root.common.dateTimeFormat = "yyyy-MM-dd HH:mm";
  115. _root.server.current = "http://127.0.0.1:8303";
  116. _root.server.optionSource = new List<string>();
  117. _root.server.optionSource.Add("http://127.0.0.1:8303");
  118. }
  119. }
  120. }
  121. catch (Exception ex)
  122. {
  123. }
  124. }
  125. }
  126. private void GetServerState()
  127. {
  128. Task.Run(async () => {
  129. var address = "";
  130. Dispatcher.Invoke(() =>
  131. {
  132. address = "http://" + ServerIPAddress.Text + ":" + "8303";
  133. });
  134. var isConnected= await ValidateServerAddress(address);
  135. if (isConnected)
  136. {
  137. _connectStatus = isConnected;
  138. Dispatcher.Invoke(() =>
  139. {
  140. ServerStatus.Text = "已开启";
  141. ServerControl.Content = "关闭";
  142. ServerIPAddress.Foreground = Brushes.Green;
  143. ServerStatus.Foreground = Brushes.Green;
  144. });
  145. CancelBusy();
  146. }
  147. else {
  148. _connectStatus = false;
  149. Dispatcher.Invoke(() =>
  150. {
  151. if (_isTestingServer)
  152. {
  153. ServerStatus.Text = "--";
  154. return;
  155. }
  156. else {
  157. ServerStatus.Text = "已关闭";
  158. ServerIPAddress.Foreground = Brushes.Red;
  159. ServerControl.Content = "开启";
  160. ServerStatus.Foreground = Brushes.Red;
  161. }
  162. });
  163. }
  164. });
  165. }
  166. private void portNum_PreviewTextInput(object sender, TextCompositionEventArgs e)
  167. {
  168. e.Handled = !char.IsDigit(e.Text, e.Text.Length - 1);
  169. }
  170. private void ipAddress_PreviewTextInput(object sender, TextCompositionEventArgs e)
  171. {
  172. e.Handled = !IsValidIpChar(e.Text);
  173. }
  174. private bool IsValidIpChar(string text)
  175. {
  176. // 检查是否是数字或.
  177. return char.IsDigit(text, 0) || text == ".";
  178. }
  179. public string GetLocalIPAddress()
  180. {
  181. string localIP = "";
  182. IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
  183. foreach (IPAddress ip in host.AddressList)
  184. {
  185. if (ip.AddressFamily == AddressFamily.InterNetwork)
  186. {
  187. localIP = ip.ToString();
  188. break;
  189. }
  190. }
  191. ServerIPAddress.Text= localIP;
  192. return localIP;
  193. }
  194. private async void SaveAddress_Click(object sender, RoutedEventArgs e)
  195. {
  196. var ip = ipAddress.Text;
  197. var port= portNum.Text;
  198. ValidatePort(port);
  199. if (!string.IsNullOrEmpty(_validationError))
  200. {
  201. MessageBox.Show(owner: this, _validationError, "提示");
  202. return;
  203. }
  204. ValidateIpAddress(ip);
  205. if (!string.IsNullOrEmpty(_validationError))
  206. {
  207. MessageBox.Show(owner: this, _validationError, "提示");
  208. return;
  209. }
  210. var address="http://"+ ip + ":"+port;
  211. InvokeBusy("保存中...");
  212. var data=await ValidateServerAddress(address);
  213. CancelBusy();
  214. if (!string.IsNullOrEmpty(_validationError))
  215. {
  216. MessageBox.Show(owner: this, _validationError,"提示");
  217. return;
  218. }
  219. else {
  220. _root.server.current = address;
  221. var rootText=JsonConvert.SerializeObject(_root);
  222. if (!Directory.Exists(_pathApp))
  223. {
  224. Directory.CreateDirectory(_pathApp);
  225. }
  226. if (!Directory.Exists(_appStorage))
  227. {
  228. Directory.CreateDirectory(_appStorage);
  229. }
  230. File.WriteAllText(_configurePath, rootText);
  231. MessageBox.Show(owner: this, "保存成功!", "提示");
  232. }
  233. }
  234. private void ValidateIpAddress(string ipAddress)
  235. {
  236. if (!string.IsNullOrEmpty(ipAddress))
  237. {
  238. var isIP = IPAddress.TryParse(ipAddress, out _);
  239. if (isIP)
  240. {
  241. _validationError = null;
  242. }
  243. else {
  244. _validationError = "IP 地址格式不正确!";
  245. }
  246. }
  247. else
  248. {
  249. _validationError = null;
  250. }
  251. }
  252. private async Task<bool> ValidateServerAddress(string address)
  253. {
  254. try
  255. {
  256. InvokeBusy("检测中...");
  257. var client = new JsonRpcClient();
  258. var clientEngine = new JsonRpcHttpClientEngine(address);
  259. client.UseEngine(clientEngine);
  260. var loginService = client?.CreateProxy<ILoginService>();
  261. if (loginService != null)
  262. {
  263. _validationError = null;
  264. }
  265. else
  266. {
  267. _validationError = "服务不存在!";
  268. }
  269. var result = await loginService.CommonLoginAsync(new WingInterfaceLibrary.Request.User.CommonLoginRequest()
  270. {
  271. });
  272. if (result == null)
  273. {
  274. _validationError = "服务不存在!";
  275. return false;
  276. }
  277. if (result.LoginState == WingInterfaceLibrary.Enum.LoginStateEnum.SignOrLoginFail ||
  278. result.LoginState == WingInterfaceLibrary.Enum.LoginStateEnum.PasswordIncorrect
  279. )
  280. {
  281. _validationError = null;
  282. return true;
  283. }
  284. }
  285. catch (RpcException ex)
  286. {
  287. _validationError = null;
  288. return true;
  289. }
  290. catch (Exception ex)
  291. {
  292. _validationError = "服务不存在!";
  293. return false;
  294. }
  295. finally {
  296. if (!_isTestingServer)
  297. {
  298. CancelBusy();
  299. }
  300. }
  301. return true;
  302. }
  303. private void ValidatePort(string port)
  304. {
  305. var success=int.TryParse(port, out int value);
  306. if (string.IsNullOrEmpty(port)||!success)
  307. {
  308. _validationError = "请输入端口号!";
  309. }
  310. if (value <= 0 || value > 65535)
  311. {
  312. _validationError = "端口号需要在 1 到 65535!";
  313. }
  314. else
  315. {
  316. _validationError = null;
  317. }
  318. }
  319. private void ServerControl_Click(object sender, RoutedEventArgs e)
  320. {
  321. ControlServer(ServerControl.Content == "开启");
  322. }
  323. private void RestartServer_Click(object sender, RoutedEventArgs e)
  324. {
  325. Task.Run(() => {
  326. InvokeBusy("重启中...");
  327. ControlServer(false,true);
  328. Thread.Sleep(3000);
  329. ControlServer(true,true);
  330. });
  331. }
  332. private void InvokeBusy(string busyText="繁忙中...")
  333. {
  334. Dispatcher.Invoke(() =>
  335. {
  336. LoaderBorder.Visibility = Visibility.Visible;
  337. IsHitTestVisible = false;
  338. ToolStatus.Text = busyText;
  339. });
  340. }
  341. private void CancelBusy()
  342. {
  343. Dispatcher.Invoke(() =>
  344. {
  345. LoaderBorder.Visibility = Visibility.Collapsed;
  346. IsHitTestVisible = true;
  347. ToolStatus.Text = "繁忙中...";
  348. });
  349. }
  350. private void ControlServer(bool isOpen, bool isRestart=false)
  351. {
  352. var targetPath = isOpen ? _serverStartPath : _serverClosePath;
  353. ProcessStartInfo processInfo2 = new ProcessStartInfo(targetPath)
  354. {
  355. CreateNoWindow = true,
  356. UseShellExecute=false,
  357. RedirectStandardError=true,
  358. RedirectStandardOutput=true,
  359. Verb = "runas",
  360. // 不使用操作系统外壳程序启动进程
  361. };
  362. Process.Start(processInfo2);
  363. Dispatcher.Invoke(() =>
  364. {
  365. ServerStatus.Text = "--";
  366. });
  367. Task.Run
  368. (() =>
  369. {
  370. if (isOpen)
  371. {
  372. int count = 0;
  373. InvokeBusy("开启中...");
  374. _isTestingServer = true;
  375. while (_isTestingServer)
  376. {
  377. count++;
  378. Thread.Sleep(3000);
  379. InvokeBusy("开启中...");
  380. GetServerState();
  381. if (_connectStatus)
  382. {
  383. _isTestingServer=false;
  384. var tip = isRestart ? "服务器已重启" : "服务器已开启";
  385. MessageBox.Show(owner: this, tip, "提示");
  386. break;
  387. }
  388. if (count == 15)
  389. {
  390. _isTestingServer = false;
  391. CancelBusy();
  392. Dispatcher.Invoke(() =>
  393. {
  394. ServerStatus.Text = _isTestingServer ? "--" : "已关闭";
  395. ServerIPAddress.Foreground = Brushes.Red;
  396. ServerStatus.Foreground = Brushes.Red;
  397. ServerControl.Content = "开启";
  398. MessageBox.Show(owner: this, "服务器开启失败", "错误!");
  399. });
  400. break;
  401. }
  402. }
  403. CancelBusy();
  404. }
  405. else
  406. {
  407. Task.Run(() =>
  408. {
  409. InvokeBusy("关闭中...");
  410. Thread.Sleep(3000);
  411. CancelBusy();
  412. Dispatcher.Invoke(() =>
  413. {
  414. ServerStatus.Text = "已关闭";
  415. ServerControl.Content = "开启";
  416. ServerIPAddress.Foreground = Brushes.Red;
  417. ServerStatus.Foreground = Brushes.Red;
  418. _connectStatus = false;
  419. if (!isRestart)
  420. {
  421. MessageBox.Show(owner: this, "服务器已关闭", "提示");
  422. }
  423. });
  424. });
  425. }
  426. });
  427. }
  428. }
  429. }