ServerGrid.cs 42 KB

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