ServerGrid.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.ServiceProcess;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Windows;
  13. using System.Windows.Controls;
  14. using System.Windows.Media.Imaging;
  15. using Comal.Classes;
  16. using Comal.Stores;
  17. using InABox.Client.IPC;
  18. using InABox.Clients;
  19. using InABox.Configuration;
  20. using InABox.Core;
  21. using InABox.Database;
  22. using InABox.Database.SQLite;
  23. using InABox.DynamicGrid;
  24. using InABox.IPC;
  25. using InABox.Rpc;
  26. using InABox.Wpf.Editors;
  27. using InABox.WPF;
  28. using PRSClasses;
  29. using PRSServer.Forms;
  30. using PRSServer.Forms.DatabaseLicense;
  31. using RestSharp;
  32. using Method = RestSharp.Method;
  33. namespace PRSServer
  34. {
  35. class ServerStartupSettings : BaseObject, ILocalConfigurationSettings
  36. {
  37. public List<string> StartServers { get; set; } = new();
  38. }
  39. public class ServerGrid : DynamicGrid<Server>
  40. {
  41. private Task? _monitor;
  42. private ConcurrentBag<ServiceController> _services = new();
  43. private Button _channelButton;
  44. private Button _statusButton;
  45. public ServerGrid()
  46. {
  47. Options.AddRange(DynamicGridOption.AddRows, DynamicGridOption.EditRows, DynamicGridOption.DeleteRows, DynamicGridOption.ShowHelp);
  48. ActionColumns.Add(new DynamicImageColumn(TypeImage)
  49. { Position = DynamicActionColumnPosition.Start, ToolTip = TypeToolTip });
  50. ActionColumns.Add(new DynamicImageColumn(SecureImage)
  51. { Position = DynamicActionColumnPosition.Start, ToolTip = SecureToolTip });
  52. ActionColumns.Add(new DynamicImageColumn(StateImage, StateAction)
  53. { Position = DynamicActionColumnPosition.End, ToolTip = StateToolTip });
  54. ActionColumns.Add(new DynamicMenuColumn(CreateServerMenu,ServerMenuStatus)
  55. { Position = DynamicActionColumnPosition.End, ToolTip = MenuToolTip });
  56. RowHeight = 40;
  57. FontSize = 14;
  58. _channelButton = AddButton("", Properties.Resources.autoupdate.AsBitmapImage(), "Change Update Channel", EditUpdateChannel_Click);
  59. _statusButton = AddButton("", Properties.Resources.secure.AsBitmapImage(), "Check Service Status", ShowServiceStatus);
  60. }
  61. private BitmapImage secureImage = Properties.Resources.secure.AsBitmapImage();
  62. private BitmapImage insecureImage = Properties.Resources.insecure.AsBitmapImage();
  63. private BitmapImage? SecureImage(CoreRow? row)
  64. {
  65. if(row is null)
  66. {
  67. return secureImage;
  68. }
  69. else
  70. {
  71. var key = row.Get<Server, string>(x => x.Key);
  72. if(SecureConnections.TryGetValue(key, out var secure))
  73. {
  74. return secure
  75. ? secureImage
  76. : insecureImage;
  77. }
  78. else
  79. {
  80. return null;
  81. }
  82. }
  83. }
  84. private FrameworkElement? SecureToolTip(DynamicActionColumn column, CoreRow? row)
  85. {
  86. if(row is null)
  87. {
  88. return column.TextToolTip("Connection Security");
  89. }
  90. else
  91. {
  92. var key = row.Get<Server, string>(x => x.Key);
  93. if (SecureConnections.TryGetValue(key, out var secure))
  94. {
  95. return secure
  96. ? column.TextToolTip("Secure (HTTPS) Connection")
  97. : column.TextToolTip("Insecure (HTTP) Connection");
  98. }
  99. else
  100. {
  101. return null;
  102. }
  103. }
  104. }
  105. private DynamicMenuStatus ServerMenuStatus(CoreRow arg)
  106. {
  107. if (arg == null)
  108. return DynamicMenuStatus.Hidden;
  109. var type = arg.Get<Server, ServerType>(x => x.Type);
  110. var service = GetService(arg.Get<Server, string>(c => c.Key));
  111. var running = service?.Status == ServiceControllerStatus.Running;
  112. if ((type == ServerType.Database) || (type == ServerType.Web) || (type == ServerType.Schedule))
  113. {
  114. return running
  115. ? DynamicMenuStatus.Enabled
  116. : DynamicMenuStatus.Disabled;
  117. }
  118. return running
  119. ? DynamicMenuStatus.Enabled
  120. : DynamicMenuStatus.Hidden;
  121. }
  122. private void CreateServerMenu(DynamicMenuColumn column, CoreRow? row)
  123. {
  124. if (row == null)
  125. return;
  126. var status = ServerMenuStatus(row);
  127. if (status == DynamicMenuStatus.Hidden)
  128. return;
  129. var type = row.Get<Server, ServerType>(x => x.Type);
  130. var key = row.Get<Server, String>(x => x.Key);
  131. column.AddItem(
  132. "View Console",
  133. Properties.Resources.target,
  134. (row) => StartConsole(row, key),
  135. null,
  136. status == DynamicMenuStatus.Enabled && !_consoles.ContainsKey(key)
  137. );
  138. if (type.Equals(ServerType.Database))
  139. {
  140. column.AddSeparator();
  141. column.AddItem(
  142. "Custom Fields",
  143. Properties.Resources.service,
  144. (row) => EditCustomFields(row),
  145. null,
  146. status == DynamicMenuStatus.Enabled
  147. );
  148. column.AddItem(
  149. "Database Scripts",
  150. Properties.Resources.script,
  151. (row) => EditDatabaseScripts(row),
  152. null,
  153. status == DynamicMenuStatus.Enabled
  154. );
  155. column.AddSeparator();
  156. column.AddItem(
  157. "Update License",
  158. Properties.Resources.key,
  159. (row) => UpdateDatabaseLicense(row),
  160. null,
  161. status == DynamicMenuStatus.Enabled
  162. );
  163. column.AddSeparator();
  164. column.AddItem(
  165. "Manage Deletions",
  166. Properties.Resources.delete,
  167. (row) => ManageDeletions(row),
  168. null,
  169. status == DynamicMenuStatus.Enabled
  170. );
  171. }
  172. else if (type.Equals(ServerType.Web))
  173. {
  174. column.AddSeparator();
  175. column.AddItem(
  176. "Edit Templates",
  177. Properties.Resources.script,
  178. (row) => EditWebTemplates(row),
  179. null,
  180. status == DynamicMenuStatus.Enabled
  181. );
  182. column.AddItem(
  183. "Edit Styles",
  184. Properties.Resources.css,
  185. (row) => EditWebStyles(row),
  186. null,
  187. status == DynamicMenuStatus.Enabled
  188. );
  189. column.AddItem(
  190. "Edit Documents",
  191. Properties.Resources.pdf,
  192. (row) => EditWebDocuments(row),
  193. null,
  194. status == DynamicMenuStatus.Enabled
  195. );
  196. column.AddSeparator();
  197. column.AddItem(
  198. "PRS Mobile Settings",
  199. Properties.Resources.web,
  200. (row) => PRSMobileSettings(row),
  201. null,
  202. status == DynamicMenuStatus.Enabled
  203. );
  204. }
  205. else if (type.Equals(ServerType.Schedule))
  206. {
  207. column.AddSeparator();
  208. column.AddItem(
  209. "Scheduled Scripts",
  210. Properties.Resources.script,
  211. (row) => EditScheduledScripts(row),
  212. null,
  213. status == DynamicMenuStatus.Enabled
  214. );
  215. }
  216. }
  217. private ServiceController? GetService(string key)
  218. {
  219. return _services.FirstOrDefault(x => string.Equals(x.ServiceName, key));
  220. }
  221. protected override void ShowHelp(string slug)
  222. {
  223. base.ShowHelp("Server_Configuration");
  224. }
  225. public void BeforeUpdate()
  226. {
  227. var sections = PRSService.GetConfiguration().LoadAll();
  228. RefreshServices(sections);
  229. var closed = new List<string>();
  230. foreach (var service in _services)
  231. {
  232. if(service.Status == ServiceControllerStatus.Running)
  233. {
  234. service.Stop();
  235. closed.Add(service.ServiceName);
  236. }
  237. }
  238. var config = PRSService.GetConfiguration<ServerStartupSettings>();
  239. var startupSettings = config.Load();
  240. startupSettings.StartServers = closed;
  241. config.Save(startupSettings);
  242. }
  243. #region Grid Handling
  244. private void RefreshServices(Dictionary<string, ServerSettings> sections)
  245. {
  246. Interlocked.Exchange(
  247. ref _services,
  248. new ConcurrentBag<ServiceController>(
  249. ServiceController.GetServices().Where(x => sections.ContainsKey(x.ServiceName))
  250. )
  251. );
  252. }
  253. private Dictionary<string, bool> SecureConnections { get; set; } = new Dictionary<string, bool>();
  254. private HashSet<string> LoadingInfos = new HashSet<string>();
  255. protected override void Reload(Filters<Server> criteria, Columns<Server> columns, ref SortOrder<Server>? sort,
  256. Action<CoreTable?, Exception?> action)
  257. {
  258. var table = new CoreTable();
  259. table.LoadColumns(typeof(Server));
  260. var sections = PRSService.GetConfiguration().LoadAll();
  261. RefreshServices(sections);
  262. var startupConfig = PRSService.GetConfiguration<ServerStartupSettings>();
  263. var startupSettings = startupConfig.Load();
  264. foreach (var startup in startupSettings.StartServers)
  265. {
  266. _services.FirstOrDefault(x => x.ServiceName == startup)?.Start();
  267. }
  268. startupSettings.StartServers.Clear();
  269. startupConfig.Save(startupSettings);
  270. foreach (var section in sections.OrderBy(x => x.Value.Type))
  271. {
  272. var server = section.Value.CreateServer(section.Key);
  273. var service = _services.FirstOrDefault(x => string.Equals(x.ServiceName, section.Key));
  274. var row = table.NewRow();
  275. table.LoadRow(row, server);
  276. table.Rows.Add(row);
  277. }
  278. if (table.Rows.Any(x => x.Get<Server, ServerType>(x => x.Type) == ServerType.Certificate))
  279. {
  280. foreach (var row in table.Rows.Where(x => x.Get<Server, ServerType>(x => x.Type) == ServerType.Web))
  281. {
  282. var key = row.Get<Server, string>(x => x.Key);
  283. var props = row.ToObject<Server>().Properties as WebServerProperties;
  284. if (props != null)
  285. {
  286. Task.Run(() =>
  287. {
  288. bool IsHTTPs = false;
  289. var client = new HttpClient { BaseAddress = new Uri($"https://127.0.0.1:{props.ListenPort}") };
  290. try
  291. {
  292. client.GetAsync("/").Wait();
  293. SecureConnections[key] = true;
  294. }
  295. catch (Exception e)
  296. {
  297. System.Console.WriteLine(e);
  298. throw;
  299. }
  300. // try
  301. // {
  302. // client.GetAsync("operations").Wait();
  303. // URL = $"https://{url}";
  304. // isHTTPS = true;
  305. // }
  306. // catch (Exception)
  307. // {
  308. // URL = $"http://{url}";
  309. // isHTTPS = false;
  310. // }
  311. // }
  312. // return URL;
  313. });
  314. }
  315. }
  316. foreach (var row in table.Rows.Where(x => x.Get<Server, ServerType>(x => x.Type) == ServerType.Database))
  317. {
  318. var key = row.Get<Server, string>(x => x.Key);
  319. var service = GetService(key);
  320. if (service is not null && service.Status == ServiceControllerStatus.Running)
  321. {
  322. if (!LoadingInfos.Contains(key))
  323. {
  324. LoadingInfos.Add(key);
  325. Task.Run(() =>
  326. {
  327. while (true)
  328. {
  329. var client = new RpcClientPipeTransport(DatabaseServerProperties.GetPipeName(key));
  330. //var client = IPCClientFactory.GetClient(DatabaseServerProperties.GetPipeName(key));
  331. var response = client.Info();
  332. //var response = client.Send(IPCMessage.Info(new InfoRequest()), 10_000).GetResponse<InfoResponse>();
  333. if (response != null)
  334. {
  335. SecureConnections[key] = response.IsHTTPS;
  336. break;
  337. }
  338. else
  339. {
  340. SecureConnections.Remove(key);
  341. var service = GetService(key);
  342. if (service is null || service.Status != ServiceControllerStatus.Running)
  343. break;
  344. }
  345. }
  346. Dispatcher.Invoke(() =>
  347. {
  348. InvalidateRow(row);
  349. });
  350. LoadingInfos.Remove(key);
  351. });
  352. }
  353. }
  354. else
  355. {
  356. if(SecureConnections.TryGetValue(key, out var info))
  357. {
  358. SecureConnections.Remove(key);
  359. }
  360. }
  361. }
  362. }
  363. action(table, null);
  364. _monitor ??= Task.Run(() =>
  365. {
  366. while (true)
  367. {
  368. try
  369. {
  370. var bRefresh = false;
  371. foreach (var service in _services)
  372. {
  373. var oldstatus = service.Status;
  374. service.Refresh();
  375. bRefresh = bRefresh || service.Status != oldstatus;
  376. /*if ((oldstatus != ServiceControllerStatus.Stopped) && (service.Status == ServiceControllerStatus.Stopped))
  377. Dispatcher.Invoke(() => StopConsole(service.ServiceName));*/
  378. }
  379. if (bRefresh)
  380. Dispatcher.Invoke(() => { Refresh(false, true); });
  381. }
  382. catch (Exception e)
  383. {
  384. }
  385. Task.Delay(500).Wait();
  386. }
  387. });
  388. }
  389. // protected override void SelectItems(CoreRow[] rows)
  390. // {
  391. // base.SelectItems(rows);
  392. // if (rows != null && rows.Length == 1)
  393. // {
  394. // var type = rows.First().Get<Server, ServerType>(x => x.Type);
  395. // DatabaseLicense.Visibility = Equals(type, ServerType.Database) ? Visibility.Visible : Visibility.Collapsed;
  396. // DatabaseCustomFields.Visibility = Equals(type, ServerType.Database) ? Visibility.Visible : Visibility.Collapsed;
  397. // DatabaseScripts.Visibility = Equals(type, ServerType.Database) ? Visibility.Visible : Visibility.Collapsed;
  398. //
  399. // EditWebSettings.Visibility = Equals(type, ServerType.Web) ? Visibility.Visible : Visibility.Collapsed;
  400. //
  401. // ScheduledScripts.Visibility = type == ServerType.Schedule ? Visibility.Visible : Visibility.Collapsed;
  402. // }
  403. // else
  404. // {
  405. // EditWebSettings.Visibility = Visibility.Collapsed;
  406. // DatabaseLicense.Visibility = Visibility.Collapsed;
  407. // DatabaseCustomFields.Visibility = Visibility.Collapsed;
  408. // DatabaseScripts.Visibility = Visibility.Collapsed;
  409. // ScheduledScripts.Visibility = Visibility.Collapsed;
  410. // }
  411. // }
  412. protected override Server LoadItem(CoreRow row)
  413. {
  414. var key = row.Get<Server, string>(x => x.Key);
  415. var settings = PRSService.GetConfiguration(key).Load();
  416. return settings.CreateServer(key);
  417. }
  418. private string CreateKey(ServerType type)
  419. {
  420. var services = ServiceController.GetServices();
  421. var key = string.Format("PRS{0}", type.ToString());
  422. var i = 1;
  423. while (services.Any(x => string.Equals(key, x.ServiceName)))
  424. key = string.Format("PRS{0}_{1}", type.ToString(), i++);
  425. return key;
  426. }
  427. private void CreateMenu(ContextMenu parent, string header, ServerType server, Type properties)
  428. {
  429. var menu = new MenuItem();
  430. menu.Header = header;
  431. menu.Tag = properties;
  432. menu.Icon = new Image() { Source = _typeimages[server] };
  433. menu.IsCheckable = false;
  434. menu.Click += (o, e) =>
  435. {
  436. var itemtype = ((o as MenuItem)?.Tag as Type)!;
  437. var props = (Activator.CreateInstance(itemtype) as ServerProperties)!;
  438. if (EditProperties(properties, props, true))
  439. {
  440. var server = CreateItem();
  441. server.Key = CreateKey(props.Type());
  442. server.Type = props.Type();
  443. server.Properties = props;
  444. SaveItem(server);
  445. Refresh(false, true);
  446. }
  447. };
  448. parent.Items.Add(menu);
  449. }
  450. protected override void DoAdd(bool OpenEditorOnDirectEdit = false)
  451. {
  452. var menu = new ContextMenu();
  453. CreateMenu(menu, "Database", ServerType.Database, typeof(DatabaseServerProperties));
  454. CreateMenu(menu, "GPS Connector", ServerType.GPS, typeof(GPSServerProperties));
  455. if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.AutoDiscovery))
  456. CreateMenu(menu, "Auto Discovery", ServerType.AutoDiscovery, typeof(AutoDiscoveryServerProperties));
  457. CreateMenu(menu, "Scheduler", ServerType.Schedule, typeof(ScheduleServerProperties));
  458. CreateMenu(menu, "Web Service", ServerType.Web, typeof(WebServerProperties));
  459. if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.Certificate))
  460. CreateMenu(menu, "HTTPS Certificate Engine", ServerType.Certificate, typeof(CertificateEngineProperties));
  461. menu.IsOpen = true;
  462. }
  463. protected override void DoEdit()
  464. {
  465. if (!SelectedRows.Any())
  466. return;
  467. var server = LoadItem(SelectedRows.First());
  468. var service = GetService(server.Key);
  469. var enabled = service == null || service.Status == ServiceControllerStatus.Stopped;
  470. if (EditProperties(server.Properties.GetType(), server.Properties, enabled))
  471. {
  472. server.Name = server.Properties.Name;
  473. SaveItem(server);
  474. Refresh(false, true);
  475. }
  476. }
  477. public override void SaveItem(Server item)
  478. {
  479. var settings = new ServerSettings();
  480. settings.Type = item.Type;
  481. settings.Properties = Serialization.Serialize(item.Properties, false);
  482. PRSService.GetConfiguration(item.Key).Save(settings);
  483. ReconfigureService(item);
  484. }
  485. private bool isServiceChanged(Server server, ServiceController? service, string newDisplayName)
  486. {
  487. return newDisplayName != service?.DisplayName || (server.Properties.HasOriginalValue(x => x.Username) && server.Properties.GetOriginalValue(x => x.Username) != server.Properties.Username);
  488. }
  489. protected override bool CanDeleteItems(params CoreRow[] rows)
  490. {
  491. var bOK = true;
  492. foreach (var row in rows)
  493. {
  494. var service = GetService(row.Get<Server, string>(x => x.Key));
  495. if (service != null && service.Status != ServiceControllerStatus.Stopped)
  496. bOK = false;
  497. }
  498. return bOK;
  499. }
  500. protected override void DeleteItems(params CoreRow[] rows)
  501. {
  502. foreach (var row in rows)
  503. {
  504. var key = row.Get<Server, string>(x => x.Key);
  505. Interlocked.Exchange(
  506. ref _services,
  507. new ConcurrentBag<ServiceController>(
  508. _services.Where(x => !string.Equals(x.ServiceName, key))
  509. )
  510. );
  511. PRSService.GetConfiguration(key).Delete();
  512. var serverType = row.Get<Server, ServerType>(x => x.Type);
  513. if (serverType == ServerType.Certificate)
  514. {
  515. if (File.Exists(CertificateEngine.CertificateFile))
  516. {
  517. File.Delete(CertificateEngine.CertificateFile);
  518. }
  519. }
  520. PRSServiceInstaller.UninstallService(key);
  521. }
  522. }
  523. protected override void DefineLookups(ILookupEditorControl sender, Server[] items)
  524. {
  525. if(sender.EditorDefinition is ComboLookupEditor lookup && lookup.Type == typeof(DatabaseServerLookupGenerator))
  526. {
  527. base.DefineLookups(sender, Data.Rows.Select(x => x.ToObject<Server>()).ToArray());
  528. }
  529. else
  530. {
  531. base.DefineLookups(sender, items);
  532. }
  533. }
  534. #endregion
  535. #region Server Configuration
  536. private bool EditUpdateChannel_Click(Button arg1, CoreRow[] arg2)
  537. {
  538. var settings = new LocalConfiguration<AutoUpdateSettings>().Load();
  539. var editable = settings.ToEditable();
  540. var buttons = new DynamicEditorButtons()
  541. {
  542. new DynamicEditorButton(
  543. "",
  544. Properties.Resources.help.AsBitmapImage(),
  545. null,
  546. (o, e) => base.ShowHelp("Automatic_Updates"))
  547. };
  548. var propertyEditor = new DynamicEditorForm(typeof(EditableAutoUpdateSettings), null, buttons);
  549. propertyEditor.OnDefineEditor += PropertyEditor_OnDefineEditor;
  550. propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
  551. propertyEditor.Items = new BaseObject[] { editable };
  552. if (propertyEditor.ShowDialog() == true)
  553. {
  554. settings.FromEditable(editable);
  555. new LocalConfiguration<AutoUpdateSettings>().Save(settings);
  556. }
  557. return false;
  558. }
  559. private BaseEditor? PropertyEditor_OnDefineEditor(object item, DynamicGridColumn column)
  560. {
  561. if (string.Equals(column.ColumnName, "Elevated"))
  562. return new NullEditor();
  563. var result = GetEditor(item, column);
  564. if (result != null)
  565. result = result.CloneEditor();
  566. return result;
  567. }
  568. private void ReconfigureService(Server item)
  569. {
  570. var service = GetService(item.Key);
  571. var newDisplayName = "PRS - " + item.Properties.Name;
  572. string? username = item.Properties.Username;
  573. if (!isServiceChanged(item, service, newDisplayName)) return;
  574. string? password = null;
  575. if (!string.IsNullOrWhiteSpace(username))
  576. {
  577. var passwordEditor = new PasswordDialog(string.Format("Enter password for {0}", username));
  578. if(passwordEditor.ShowDialog() == true)
  579. {
  580. password = passwordEditor.Password;
  581. }
  582. else
  583. {
  584. password = null;
  585. }
  586. }
  587. else
  588. {
  589. username = null;
  590. }
  591. if (service == null)
  592. try
  593. {
  594. using (new WaitCursor())
  595. {
  596. PRSServiceInstaller.InstallService(
  597. item.Key,
  598. item.Properties.Name,
  599. newDisplayName,
  600. username,
  601. password
  602. );
  603. }
  604. }
  605. catch (Exception e)
  606. {
  607. MessageBox.Show(string.Format("Error Installing {0}: {1}", item.Key, e.Message));
  608. }
  609. else
  610. try
  611. {
  612. using (new WaitCursor())
  613. {
  614. PRSServiceInstaller.ChangeService(
  615. item.Key,
  616. item.Properties.Name,
  617. newDisplayName,
  618. username,
  619. password
  620. );
  621. }
  622. }
  623. catch (Exception e)
  624. {
  625. MessageBox.Show(string.Format("Error Configuring {0}: {1}", item.Key, e.Message));
  626. }
  627. }
  628. public bool EditProperties(Type type, ServerProperties item, bool enabled)
  629. {
  630. var pages = new DynamicEditorPages();
  631. if (type == typeof(DatabaseServerProperties))
  632. {
  633. pages.Add(new SMSProviderGrid(!enabled));
  634. }
  635. var buttons = new DynamicEditorButtons();
  636. buttons.Add(
  637. "",
  638. Properties.Resources.help.AsBitmapImage(),
  639. item,
  640. (f, i) =>
  641. {
  642. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + type.Name.SplitCamelCase().Replace(" ", "_"))
  643. { UseShellExecute = true });
  644. }
  645. );
  646. var propertyEditor = new DynamicEditorForm(type, pages, buttons);
  647. if(type == typeof(DatabaseServerProperties))
  648. {
  649. propertyEditor.OnSaveItem += (o, e) =>
  650. {
  651. propertyEditor.UnloadEditorPages(false);
  652. propertyEditor.UnloadEditorPages(true);
  653. };
  654. }
  655. propertyEditor.ReadOnly = !enabled;
  656. propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
  657. propertyEditor.Items = new BaseObject[] { item };
  658. return propertyEditor.ShowDialog() == true;
  659. }
  660. #endregion
  661. #region Service Start / Stop Actions
  662. private readonly Dictionary<int, BitmapImage> _stateimages = new()
  663. {
  664. { 0, Properties.Resources.warning.AsBitmapImage() },
  665. { (int)ServiceControllerStatus.Stopped, Properties.Resources.pause.AsBitmapImage() },
  666. { (int)ServiceControllerStatus.StartPending, Properties.Resources.working.AsBitmapImage() },
  667. { (int)ServiceControllerStatus.StopPending, Properties.Resources.working.AsBitmapImage() },
  668. { (int)ServiceControllerStatus.Running, Properties.Resources.tick.AsBitmapImage() },
  669. { (int)ServiceControllerStatus.ContinuePending, Properties.Resources.working.AsBitmapImage() },
  670. { (int)ServiceControllerStatus.PausePending, Properties.Resources.working.AsBitmapImage() },
  671. { (int)ServiceControllerStatus.Paused, Properties.Resources.pause.AsBitmapImage() }
  672. };
  673. private BitmapImage StateImage(CoreRow? arg)
  674. {
  675. if (arg == null)
  676. return Properties.Resources.tick.AsBitmapImage();
  677. var service = GetService(arg.Get<Server, string>(c => c.Key));
  678. var state = service != null ? (int)service.Status : 0;
  679. return _stateimages[state];
  680. }
  681. private FrameworkElement? StateToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  682. {
  683. if (arg2 == null)
  684. return null;
  685. var service = GetService(arg2.Get<Server, string>(c => c.Key));
  686. return arg1.TextToolTip(service != null ? "Current State: " + service.Status : "Not Installed");
  687. }
  688. private FrameworkElement? MenuToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  689. {
  690. return arg2 != null ? arg1.TextToolTip("Server Options") : null;
  691. }
  692. private bool StateAction(CoreRow? arg)
  693. {
  694. if (arg == null)
  695. return false;
  696. var key = arg.Get<Server, string>(c => c.Key);
  697. var service = GetService(arg.Get<Server, string>(c => c.Key));
  698. if (service != null)
  699. {
  700. Task? task;
  701. if (service.Status == ServiceControllerStatus.Running)
  702. {
  703. task = Task.Run(() => { service.Stop(); });
  704. //StopConsole(key);
  705. }
  706. else if (service.Status == ServiceControllerStatus.Stopped)
  707. {
  708. task = Task.Run(() => {
  709. service.Start();
  710. });
  711. StartConsole(arg,key);
  712. }
  713. else if (service.Status == ServiceControllerStatus.Paused)
  714. {
  715. task = Task.Run(() => { service.Continue(); });
  716. }
  717. else
  718. {
  719. MessageBox.Show(string.Format("Invalid Service State ({0})", service.Status.ToString()));
  720. return false;
  721. }
  722. task?.ContinueWith((e) =>
  723. {
  724. if (e.Exception?.InnerException is { } inner)
  725. {
  726. if(inner.InnerException != null)
  727. {
  728. MessageBox.Show(String.Format("Error while running service:\n{0}", inner.InnerException.Message));
  729. }
  730. else
  731. {
  732. MessageBox.Show(String.Format("Error while running service:\n{0}", inner.Message));
  733. }
  734. PRSServiceInstaller.UninstallService(arg.Get<Server, string>(x => x.Key));
  735. Refresh(false, true);
  736. }
  737. }, TaskScheduler.FromCurrentSynchronizationContext());
  738. return true;
  739. }
  740. MessageBox.Show("Cannot find Service - is it installed?");
  741. return false;
  742. }
  743. public void StopAll()
  744. {
  745. foreach (var service in _services.ToArray())
  746. if (service.Status == ServiceControllerStatus.Running)
  747. Task.Run(() => { service.Stop(); });
  748. }
  749. #endregion
  750. #region Server Type Images
  751. private readonly Dictionary<ServerType, BitmapImage> _typeimages = new()
  752. {
  753. { ServerType.Database, Properties.Resources.database.AsBitmapImage() },
  754. { ServerType.GPS, Properties.Resources.gps.AsBitmapImage() },
  755. { ServerType.AutoDiscovery, Properties.Resources.autodiscover.AsBitmapImage() },
  756. { ServerType.Schedule, Properties.Resources.schedule.AsBitmapImage() },
  757. { ServerType.Web, Properties.Resources.web.AsBitmapImage() },
  758. { ServerType.Certificate, Properties.Resources.certificate.AsBitmapImage() }
  759. };
  760. private BitmapImage TypeImage(CoreRow? arg)
  761. {
  762. if (arg == null)
  763. return Properties.Resources.help.AsBitmapImage();
  764. var type = arg.Get<Server, ServerType>(c => c.Type);
  765. return _typeimages[type];
  766. }
  767. private FrameworkElement? TypeToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  768. {
  769. if (arg2 == null)
  770. return null;
  771. return arg1.TextToolTip(string.Format("{0} Service\nName: {1}",
  772. arg2.Get<Server, ServerType>(c => c.Type).ToString(),
  773. arg2.Get<Server, string>(c => c.Key)
  774. ));
  775. }
  776. #endregion
  777. #region Console Functions
  778. private BitmapImage? ConsoleImage(CoreRow? arg)
  779. {
  780. if (arg == null)
  781. return Properties.Resources.target.AsBitmapImage();
  782. var service = GetService(arg.Get<Server, string>(c => c.Key));
  783. var state = service != null ? (int)service.Status : 0;
  784. if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
  785. return Properties.Resources.target.AsBitmapImage();
  786. return null;
  787. }
  788. private bool ConsoleAction(CoreRow? arg)
  789. {
  790. if (arg == null)
  791. return false;
  792. var key = arg.Get<Server, string>(c => c.Key);
  793. var service = GetService(key);
  794. var state = service != null ? (int)service.Status : 0;
  795. if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
  796. StartConsole(arg, key);
  797. return false;
  798. }
  799. private Dictionary<String, Tuple<Console,int>> _consoles = new Dictionary<string, Tuple<Console,int>>();
  800. private void StartConsole(CoreRow arg, string key)
  801. {
  802. if (_consoles.ContainsKey(key))
  803. return;
  804. var name = arg.Get<Server, string>(c => c.Name);
  805. var console = new Console(key, string.Format("{0} - {1}", key, name));
  806. var window = Window.GetWindow(this);
  807. int i = 0;
  808. while (_consoles.Any(x => x.Value.Item2 == i))
  809. i++;
  810. _consoles[key] = new Tuple<Console, int>(console, i);
  811. console.Top = window.Top + (i * 50);
  812. console.Left = window.Left + window.Width + 2 + (i*50);
  813. console.Height = window.Height;
  814. console.Closing += (o, e) =>
  815. {
  816. Console c = o as Console;
  817. if (_consoles.ContainsKey(c.ServiceName))
  818. _consoles.Remove(c.ServiceName);
  819. };
  820. console.Show();
  821. }
  822. private void StopConsole(String key)
  823. {
  824. if (!_consoles.ContainsKey(key))
  825. return;
  826. Console console = _consoles[key].Item1;
  827. console.Close();
  828. }
  829. #endregion
  830. #region Individual Server Buttons
  831. // Check if a database server is running at the given url and port
  832. private bool IsDatabaseServerRunning(string url, int port)
  833. {
  834. var uri = new Uri(string.Format("{0}:{1}", url, port));
  835. var cli = new RestClient(uri);
  836. var req = new RestRequest("/classes", Method.Get) { Timeout = 20000 };
  837. try
  838. {
  839. var res = cli.Execute(req);
  840. if (res.StatusCode != HttpStatusCode.OK || res.ErrorException != null)
  841. return false;
  842. return true;
  843. }
  844. catch (Exception e)
  845. {
  846. }
  847. return false;
  848. }
  849. // The following variables keep track of whether a database is currently being used, since if two people try to access two different databases,
  850. // terrible things will ensue.
  851. private int currentServerUsers;
  852. private string? currentServerURL;
  853. private int? currentServerPort;
  854. /// <summary>
  855. /// Configures a server for the duration of an action
  856. /// </summary>
  857. /// <typeparam name="TProperties"></typeparam>
  858. /// <param name="row"></param>
  859. /// <param name="hostaddress"></param>
  860. /// <param name="portnumber"></param>
  861. /// <param name="action"></param>
  862. /// <param name="blocking">
  863. /// If blocking is set to false, then currentServerUsers must be decreased by one manually once the
  864. /// task finishes
  865. /// </param>
  866. private void ConfigureServer<TProperties>(
  867. CoreRow row,
  868. Func<TProperties, string> hostaddress,
  869. Func<TProperties, int> portnumber,
  870. Action action,
  871. bool blocking = true
  872. ) where TProperties : ServerProperties
  873. {
  874. try
  875. {
  876. if (row == null)
  877. throw new Exception("No Row Selected!");
  878. var server = LoadItem(row);
  879. if (server == null)
  880. throw new Exception("Unable to load Server!");
  881. var props = server.Properties as TProperties;
  882. if (props == null)
  883. throw new Exception("Unable to Load Properties!");
  884. var url = hostaddress(props);
  885. var port = portnumber(props);
  886. using (new WaitCursor())
  887. {
  888. if (!IsDatabaseServerRunning(url, port))
  889. throw new Exception("Database Server is not available!");
  890. }
  891. if (action != null)
  892. {
  893. if (currentServerUsers == 0)
  894. {
  895. if (currentServerURL != url || currentServerPort != port)
  896. {
  897. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  898. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  899. }
  900. currentServerURL = url;
  901. currentServerPort = port;
  902. currentServerName = null;
  903. ClientFactory.SetClientType(typeof(RestClient<>), Platform.Server, CoreUtils.GetVersion(), url, port, true);
  904. // override the need to provide credentials when configuring the database
  905. ClientFactory.SetBypass();
  906. }
  907. else
  908. {
  909. if (url != currentServerURL || port != currentServerPort)
  910. throw new Exception(string.Format("A different Database Server ({0}:{1}) is currently in use!", currentServerURL,
  911. currentServerPort));
  912. }
  913. currentServerUsers++;
  914. action();
  915. if (blocking) currentServerUsers--;
  916. }
  917. }
  918. catch (Exception e)
  919. {
  920. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  921. MessageBox.Show(e.Message);
  922. }
  923. }
  924. private string? currentServerName;
  925. private void ConfigureIPCServer<TProperties>(
  926. CoreRow row,
  927. Func<TProperties, string> hostPipeName,
  928. Action action,
  929. bool blocking = true
  930. ) where TProperties : ServerProperties
  931. {
  932. try
  933. {
  934. if (row == null)
  935. throw new Exception("No Row Selected!");
  936. var server = LoadItem(row);
  937. if (server == null)
  938. throw new Exception("Unable to load Server!");
  939. var props = server.Properties as TProperties;
  940. if (props == null)
  941. throw new Exception("Unable to Load Properties!");
  942. var pipeName = DatabaseServerProperties.GetPipeName(hostPipeName(props));
  943. if (action != null)
  944. {
  945. if (currentServerUsers == 0)
  946. {
  947. if (currentServerName != pipeName)
  948. {
  949. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  950. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  951. }
  952. currentServerPort = null;
  953. currentServerURL = null;
  954. currentServerName = pipeName;
  955. ClientFactory.SetClientType(typeof(IPCClient<>), Platform.Server, CoreUtils.GetVersion(), pipeName);
  956. using (new WaitCursor())
  957. {
  958. if (!Client.Ping())
  959. {
  960. ClientFactory.ClearClientType();
  961. throw new Exception("Database Server is not available!");
  962. }
  963. }
  964. // override the need to provide credentials when configuring the database
  965. ClientFactory.SetBypass();
  966. }
  967. else
  968. {
  969. if (pipeName != currentServerName)
  970. throw new Exception(string.Format("A different Database Server ({0}) is currently in use!", currentServerName));
  971. }
  972. currentServerUsers++;
  973. try
  974. {
  975. action();
  976. }
  977. finally
  978. {
  979. if (blocking) currentServerUsers--;
  980. }
  981. }
  982. }
  983. catch (Exception e)
  984. {
  985. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  986. MessageBox.Show(e.Message);
  987. }
  988. }
  989. private void ConfigureLocalDatabase(
  990. CoreRow row,
  991. Action action
  992. )
  993. {
  994. try
  995. {
  996. if (row == null)
  997. throw new Exception("No Row Selected!");
  998. var server = LoadItem(row);
  999. if (server == null)
  1000. throw new Exception("Unable to load Server!");
  1001. var properties = server.Properties as DatabaseServerProperties;
  1002. if (properties == null)
  1003. throw new Exception("Unable to Load Properties!");
  1004. if (!DbFactory.IsProviderSet || DbFactory.Provider is not SQLiteProvider sql || sql.URL != properties.FileName)
  1005. {
  1006. ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Server, CoreUtils.GetVersion(), "");
  1007. Progress.ShowModal("Configuring database", (progress) =>
  1008. {
  1009. DbFactory.Stores = CoreUtils.TypeList(
  1010. AppDomain.CurrentDomain.GetAssemblies(),
  1011. myType =>
  1012. myType.IsClass
  1013. && !myType.IsAbstract
  1014. && !myType.IsGenericType
  1015. && myType.GetInterfaces().Contains(typeof(IStore))
  1016. ).ToArray();
  1017. DbFactory.Provider = new SQLiteProvider(properties.FileName);
  1018. DbFactory.Start();
  1019. StoreUtils.GoogleAPIKey = properties.GoogleAPIKey;
  1020. PurchaseOrderStore.AutoIncrementPrefix = properties.PurchaseOrderPrefix;
  1021. JobStore.AutoIncrementPrefix = properties.JobPrefix;
  1022. });
  1023. }
  1024. action();
  1025. }
  1026. catch(Exception e)
  1027. {
  1028. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  1029. MessageBox.Show(e.Message);
  1030. }
  1031. }
  1032. private bool UpdateDatabaseLicense(CoreRow selectedrow)
  1033. {
  1034. ConfigureIPCServer<DatabaseServerProperties>(
  1035. selectedrow,
  1036. //x => "http://127.0.0.1",
  1037. //x => x.Port,
  1038. x => selectedrow.Get<Server, string>(x => x.Key),
  1039. () =>
  1040. {
  1041. new LicenseRenewalForm().ShowDialog();
  1042. }
  1043. );
  1044. return false;
  1045. }
  1046. private bool ManageDeletions(CoreRow row)
  1047. {
  1048. ConfigureLocalDatabase(row, () =>
  1049. {
  1050. new DeletionsWindow().ShowDialog();
  1051. });
  1052. return false;
  1053. }
  1054. private bool EditCustomFields(CoreRow selectedrow)
  1055. {
  1056. ConfigureIPCServer<DatabaseServerProperties>(
  1057. selectedrow,
  1058. //x => "http://127.0.0.1",
  1059. //x => x.Port,
  1060. x => selectedrow.Get<Server, string>(x => x.Key),
  1061. () => { new MasterList(typeof(CustomProperty), "Class", null, true).ShowDialog(); }
  1062. );
  1063. return false;
  1064. }
  1065. private bool EditDatabaseScripts(CoreRow selectedrow)
  1066. {
  1067. ConfigureIPCServer<DatabaseServerProperties>(
  1068. selectedrow,
  1069. //x => "http://127.0.0.1",
  1070. //x => x.Port,
  1071. x => selectedrow.Get<Server, string>(x => x.Key),
  1072. () => { new MasterList(typeof(Script), "Section", null, true).ShowDialog(); }
  1073. );
  1074. return false;
  1075. }
  1076. private bool EditScheduledScripts(CoreRow selectedrow)
  1077. {
  1078. ConfigureIPCServer<ScheduleServerProperties>(
  1079. selectedrow,
  1080. x => x.Server,
  1081. () => { new MasterList(typeof(ScheduledScript), "", null, true, typeof(ScheduledScriptsGrid)).ShowDialog(); }
  1082. );
  1083. return false;
  1084. }
  1085. private bool EditWebTemplates(CoreRow selectedRow)
  1086. {
  1087. ConfigureIPCServer<WebServerProperties>(
  1088. selectedRow,
  1089. x => x.Server,
  1090. () =>
  1091. {
  1092. var window = new MasterList(typeof(WebTemplate), "DataModel", "", true);
  1093. window.Closed += (e, args) => { currentServerUsers--; };
  1094. window.Show();
  1095. },
  1096. false
  1097. );
  1098. return false;
  1099. }
  1100. private bool EditWebStyles(CoreRow selectedRow)
  1101. {
  1102. ConfigureIPCServer<WebServerProperties>(
  1103. selectedRow,
  1104. x => x.Server,
  1105. () =>
  1106. {
  1107. var window = new MasterList(typeof(WebStyle), "Code", "", true);
  1108. window.Closed += (e, args) => { currentServerUsers--; };
  1109. window.Show();
  1110. },
  1111. false
  1112. );
  1113. return false;
  1114. }
  1115. private bool EditWebDocuments(CoreRow selectedRow)
  1116. {
  1117. ConfigureIPCServer<WebServerProperties>(
  1118. selectedRow,
  1119. x => x.Server,
  1120. () =>
  1121. {
  1122. var window = new MasterList(typeof(WebDocument), "Code", "", true);
  1123. window.Closed += (e, args) => { currentServerUsers--; };
  1124. window.Show();
  1125. },
  1126. false
  1127. );
  1128. return false;
  1129. }
  1130. private bool PRSMobileSettings(CoreRow selectedrow)
  1131. {
  1132. ConfigureIPCServer<WebServerProperties>(
  1133. selectedrow,
  1134. x => x.Server,
  1135. () =>
  1136. {
  1137. var editor = new DynamicEditorForm(typeof(WebSettings));
  1138. var settings = new GlobalConfiguration<WebSettings>().Load();
  1139. editor.Items = new[] { settings };
  1140. if (editor.ShowDialog() == true) new GlobalConfiguration<WebSettings>().Save(settings);
  1141. }
  1142. );
  1143. return false;
  1144. }
  1145. private bool ShowServiceStatus(Button arg1, CoreRow[] arg2)
  1146. {
  1147. List<String> domains = new List<String>();
  1148. var certservers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) == ServerType.Certificate)
  1149. .Select(row => LoadItem(row));;
  1150. foreach (var certserver in certservers)
  1151. {
  1152. var certprops = certserver.Properties as CertificateEngineProperties;
  1153. if (certprops != null)
  1154. domains.AddRange(certprops.ParseDomainNames());
  1155. }
  1156. if (!domains.Any())
  1157. domains.Add("localhost");
  1158. var servers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) != ServerType.Certificate)
  1159. .Select(row => LoadItem(row));
  1160. var statusgrid = new ServiceStatus(domains, servers);
  1161. statusgrid.ShowDialog();
  1162. return false;
  1163. }
  1164. #endregion
  1165. }
  1166. }