ServerGrid.cs 45 KB

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