ServerGrid.cs 46 KB

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