ServerGrid.cs 45 KB

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