ServerGrid.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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 is 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. if(certservice is not null)
  308. {
  309. certservice.Refresh();
  310. if (certservice.Status == ServiceControllerStatus.Running)
  311. testcertificates = true;
  312. }
  313. }
  314. foreach (var row in table.Rows)
  315. {
  316. bool bRefresh = false;
  317. var key = row.Get<Server, string>(x => x.Key);
  318. var service = GetService(key);
  319. if(service is null)
  320. {
  321. continue;
  322. }
  323. _serviceStatuses.TryGetValue(key, out var oldstatus);
  324. service.Refresh();
  325. _serviceStatuses[key] = service.Status;
  326. if (_serviceStatuses[key] != oldstatus)
  327. bRefresh = true;
  328. if (testcertificates && (_serviceStatuses[key] == ServiceControllerStatus.Running))
  329. {
  330. var type = row.Get<Server, ServerType>(x => x.Type);
  331. if (type == ServerType.Database)
  332. {
  333. _secureConnections.TryGetValue(key, out var oldsecure);
  334. if (!_pipemonitors.TryGetValue(key, out var client))
  335. {
  336. client = new RpcClientPipeTransport(DatabaseServerProperties.GetPipeName(key, true));
  337. client.Connect();
  338. _pipemonitors[key] = client;
  339. }
  340. var info = client.IsConnected()
  341. ? client.Send<RpcInfoCommand, RpcInfoParameters, RpcInfoResult>(new RpcInfoParameters()).Info
  342. : null;
  343. _secureConnections[key] = info?.IsHTTPS ?? false;
  344. bRefresh = bRefresh || (_secureConnections[key] != oldsecure);
  345. }
  346. else if (type == ServerType.Web)
  347. {
  348. var props = row.ToObject<Server>().Properties as WebServerProperties;
  349. _secureConnections.TryGetValue(key, out var oldsecure);
  350. if (!_webmonitors.TryGetValue(key, out var client))
  351. {
  352. client = new HttpClient { BaseAddress = new Uri($"https://127.0.0.1:{props.ListenPort}") };
  353. _webmonitors[key] = client;
  354. }
  355. try
  356. {
  357. client.GetAsync("/").Wait();
  358. _secureConnections[key] = true;
  359. }
  360. catch (Exception e)
  361. {
  362. _secureConnections[key] = false;
  363. }
  364. bRefresh = bRefresh || (_secureConnections[key] != oldsecure);
  365. }
  366. }
  367. else
  368. {
  369. bRefresh = bRefresh || _secureConnections.ContainsKey(key);
  370. _secureConnections.Remove(key);
  371. }
  372. if (bRefresh)
  373. Dispatcher.Invoke(() =>
  374. {
  375. if (testcertificates && (ActionColumns[1].Position != DynamicActionColumnPosition.Start))
  376. ActionColumns[1].Position = DynamicActionColumnPosition.Start;
  377. else if (!testcertificates && (ActionColumns[1].Position != DynamicActionColumnPosition.Hidden))
  378. ActionColumns[1].Position = DynamicActionColumnPosition.Hidden;
  379. Refresh(true, false);
  380. InvalidateRow(row);
  381. });
  382. }
  383. Task.Delay(TimeSpan.FromSeconds(1)).Wait();
  384. }
  385. },
  386. cancel.Token
  387. );
  388. }
  389. protected override Server LoadItem(CoreRow row)
  390. {
  391. var key = row.Get<Server, string>(x => x.Key);
  392. var settings = PRSService.GetConfiguration(key).Load();
  393. return settings.CreateServer(key);
  394. }
  395. private string CreateKey(ServerType type)
  396. {
  397. var services = ServiceController.GetServices();
  398. var key = string.Format("PRS{0}", type.ToString());
  399. var i = 1;
  400. while (services.Any(x => string.Equals(key, x.ServiceName)))
  401. key = string.Format("PRS{0}_{1}", type.ToString(), i++);
  402. return key;
  403. }
  404. private void CreateMenu(ContextMenu parent, string header, ServerType server, Type properties)
  405. {
  406. var menu = new MenuItem();
  407. menu.Header = header;
  408. menu.Tag = properties;
  409. menu.Icon = new Image() { Source = _typeimages[server] };
  410. menu.IsCheckable = false;
  411. menu.Click += (o, e) =>
  412. {
  413. var itemtype = ((o as MenuItem)?.Tag as Type)!;
  414. var props = (Activator.CreateInstance(itemtype) as ServerProperties)!;
  415. if (EditProperties(properties, props, true))
  416. {
  417. var server = CreateItem();
  418. server.Key = CreateKey(props.Type());
  419. server.Type = props.Type();
  420. server.Properties = props;
  421. SaveItem(server);
  422. Refresh(false, true);
  423. }
  424. };
  425. parent.Items.Add(menu);
  426. }
  427. protected override void DoAdd(bool OpenEditorOnDirectEdit = false)
  428. {
  429. var menu = new ContextMenu();
  430. CreateMenu(menu, "Database", ServerType.Database, typeof(DatabaseServerProperties));
  431. CreateMenu(menu, "GPS Connector", ServerType.GPS, typeof(GPSServerProperties));
  432. if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.AutoDiscovery))
  433. CreateMenu(menu, "Auto Discovery", ServerType.AutoDiscovery, typeof(AutoDiscoveryServerProperties));
  434. CreateMenu(menu, "Scheduler", ServerType.Schedule, typeof(ScheduleServerProperties));
  435. CreateMenu(menu, "Web Service", ServerType.Web, typeof(WebServerProperties));
  436. if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.Certificate))
  437. CreateMenu(menu, "HTTPS Certificate Engine", ServerType.Certificate, typeof(CertificateEngineProperties));
  438. menu.IsOpen = true;
  439. }
  440. protected override void DoEdit()
  441. {
  442. if (!SelectedRows.Any())
  443. return;
  444. var server = LoadItem(SelectedRows.First());
  445. var service = GetService(server.Key);
  446. var enabled = service == null || service.Status == ServiceControllerStatus.Stopped;
  447. if (EditProperties(server.Properties.GetType(), server.Properties, enabled))
  448. {
  449. server.Name = server.Properties.Name;
  450. SaveItem(server);
  451. Refresh(false, true);
  452. }
  453. }
  454. public override void SaveItem(Server item)
  455. {
  456. var settings = new ServerSettings();
  457. settings.Type = item.Type;
  458. settings.Properties = Serialization.Serialize(item.Properties, false);
  459. PRSService.GetConfiguration(item.Key).Save(settings);
  460. ReconfigureService(item);
  461. }
  462. private bool isServiceChanged(Server server, ServiceController? service, string newDisplayName)
  463. {
  464. return newDisplayName != service?.DisplayName || (server.Properties.HasOriginalValue(x => x.Username) && server.Properties.GetOriginalValue(x => x.Username) != server.Properties.Username);
  465. }
  466. protected override bool CanDeleteItems(params CoreRow[] rows)
  467. {
  468. var bOK = true;
  469. foreach (var row in rows)
  470. {
  471. var service = GetService(row.Get<Server, string>(x => x.Key));
  472. if (service != null && service.Status != ServiceControllerStatus.Stopped)
  473. bOK = false;
  474. }
  475. return bOK;
  476. }
  477. protected override void DeleteItems(params CoreRow[] rows)
  478. {
  479. foreach (var row in rows)
  480. {
  481. var key = row.Get<Server, string>(x => x.Key);
  482. Interlocked.Exchange(
  483. ref _services,
  484. new ConcurrentBag<ServiceController>(
  485. _services.Where(x => !string.Equals(x.ServiceName, key))
  486. )
  487. );
  488. PRSService.GetConfiguration(key).Delete();
  489. var serverType = row.Get<Server, ServerType>(x => x.Type);
  490. if (serverType == ServerType.Certificate)
  491. {
  492. if (File.Exists(CertificateEngine.CertificateFile))
  493. {
  494. File.Delete(CertificateEngine.CertificateFile);
  495. }
  496. }
  497. PRSServiceInstaller.UninstallService(key);
  498. }
  499. }
  500. protected override void DefineLookups(ILookupEditorControl sender, Server[] items, bool async = true)
  501. {
  502. if(sender.EditorDefinition is ComboLookupEditor lookup && lookup.Type == typeof(DatabaseServerLookupGenerator))
  503. {
  504. base.DefineLookups(sender, Data.Rows.Select(x => x.ToObject<Server>()).ToArray());
  505. }
  506. else
  507. {
  508. base.DefineLookups(sender, items, async);
  509. }
  510. }
  511. #endregion
  512. #region Server Configuration
  513. private bool EditUpdateChannel_Click(Button arg1, CoreRow[] arg2)
  514. {
  515. var settings = new LocalConfiguration<AutoUpdateSettings>().Load();
  516. var editable = settings.ToEditable();
  517. var buttons = new DynamicEditorButtons()
  518. {
  519. new DynamicEditorButton(
  520. "",
  521. Properties.Resources.help.AsBitmapImage(),
  522. null,
  523. (o, e) => base.ShowHelp("Automatic_Updates"))
  524. };
  525. var propertyEditor = new DynamicEditorForm(typeof(EditableAutoUpdateSettings), null, buttons);
  526. propertyEditor.OnDefineEditor += PropertyEditor_OnDefineEditor;
  527. propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
  528. propertyEditor.Items = new BaseObject[] { editable };
  529. if (propertyEditor.ShowDialog() == true)
  530. {
  531. settings.FromEditable(editable);
  532. new LocalConfiguration<AutoUpdateSettings>().Save(settings);
  533. }
  534. return false;
  535. }
  536. private BaseEditor? PropertyEditor_OnDefineEditor(object item, DynamicGridColumn column)
  537. {
  538. if (string.Equals(column.ColumnName, "Elevated"))
  539. return new NullEditor();
  540. var result = GetEditor(item, column);
  541. if (result != null)
  542. result = result.CloneEditor();
  543. return result;
  544. }
  545. private void ReconfigureService(Server item)
  546. {
  547. var service = GetService(item.Key);
  548. var newDisplayName = "PRS - " + item.Properties.Name;
  549. string? username = item.Properties.Username;
  550. if (!isServiceChanged(item, service, newDisplayName)) return;
  551. string? password = null;
  552. if (!string.IsNullOrWhiteSpace(username))
  553. {
  554. var passwordEditor = new PasswordDialog(string.Format("Enter password for {0}", username));
  555. if(passwordEditor.ShowDialog() == true)
  556. {
  557. password = passwordEditor.Password;
  558. }
  559. else
  560. {
  561. password = null;
  562. }
  563. }
  564. else
  565. {
  566. username = null;
  567. }
  568. if (service == null)
  569. try
  570. {
  571. using (new WaitCursor())
  572. {
  573. PRSServiceInstaller.InstallService(
  574. item.Key,
  575. item.Properties.Name,
  576. newDisplayName,
  577. username,
  578. password
  579. );
  580. }
  581. }
  582. catch (Exception e)
  583. {
  584. MessageBox.Show(string.Format("Error Installing {0}: {1}", item.Key, e.Message));
  585. }
  586. else
  587. try
  588. {
  589. using (new WaitCursor())
  590. {
  591. PRSServiceInstaller.ChangeService(
  592. item.Key,
  593. item.Properties.Name,
  594. newDisplayName,
  595. username,
  596. password
  597. );
  598. }
  599. }
  600. catch (Exception e)
  601. {
  602. MessageBox.Show(string.Format("Error Configuring {0}: {1}", item.Key, e.Message));
  603. }
  604. }
  605. public bool EditProperties(Type type, ServerProperties item, bool enabled)
  606. {
  607. var pages = new DynamicEditorPages();
  608. if (type == typeof(DatabaseServerProperties))
  609. {
  610. pages.Add(new SMSProviderGrid());
  611. }
  612. var buttons = new DynamicEditorButtons();
  613. buttons.Add(
  614. "",
  615. Properties.Resources.help.AsBitmapImage(),
  616. item,
  617. (f, i) =>
  618. {
  619. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + type.Name.SplitCamelCase().Replace(" ", "_"))
  620. { UseShellExecute = true });
  621. }
  622. );
  623. var propertyEditor = new DynamicEditorForm(type, pages, buttons);
  624. if(type == typeof(DatabaseServerProperties))
  625. {
  626. propertyEditor.OnSaveItem += (o, e) =>
  627. {
  628. propertyEditor.UnloadEditorPages(false);
  629. propertyEditor.UnloadEditorPages(true);
  630. };
  631. }
  632. propertyEditor.ReadOnly = !enabled;
  633. propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
  634. propertyEditor.Items = new BaseObject[] { item };
  635. return propertyEditor.ShowDialog() == true;
  636. }
  637. #endregion
  638. #region Service Start / Stop Actions
  639. private readonly Dictionary<int, BitmapImage> _stateimages = new()
  640. {
  641. { 0, Properties.Resources.warning.AsBitmapImage() },
  642. { (int)ServiceControllerStatus.Stopped, Properties.Resources.pause.AsBitmapImage() },
  643. { (int)ServiceControllerStatus.StartPending, Properties.Resources.working.AsBitmapImage() },
  644. { (int)ServiceControllerStatus.StopPending, Properties.Resources.working.AsBitmapImage() },
  645. { (int)ServiceControllerStatus.Running, Properties.Resources.tick.AsBitmapImage() },
  646. { (int)ServiceControllerStatus.ContinuePending, Properties.Resources.working.AsBitmapImage() },
  647. { (int)ServiceControllerStatus.PausePending, Properties.Resources.working.AsBitmapImage() },
  648. { (int)ServiceControllerStatus.Paused, Properties.Resources.pause.AsBitmapImage() }
  649. };
  650. private BitmapImage StateImage(CoreRow? arg)
  651. {
  652. if (arg == null)
  653. return Properties.Resources.tick.AsBitmapImage();
  654. var key = arg.Get<Server, string>(c => c.Key);
  655. var service = GetService(key);
  656. int state = service != null ? (int)service.Status : 0;
  657. return _stateimages[state];
  658. }
  659. private FrameworkElement? StateToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  660. {
  661. if (arg2 == null)
  662. return null;
  663. var service = GetService(arg2.Get<Server, string>(c => c.Key));
  664. return arg1.TextToolTip(service != null ? "Current State: " + service.Status : "Not Installed");
  665. }
  666. private FrameworkElement? MenuToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  667. {
  668. return arg2 != null ? arg1.TextToolTip("Server Options") : null;
  669. }
  670. private bool StateAction(CoreRow? arg)
  671. {
  672. if (arg == null)
  673. return false;
  674. var key = arg.Get<Server, string>(c => c.Key);
  675. var service = GetService(arg.Get<Server, string>(c => c.Key));
  676. if (service != null)
  677. {
  678. Task? task;
  679. if (service.Status == ServiceControllerStatus.Running)
  680. {
  681. task = Task.Run(
  682. () =>
  683. {
  684. service.Stop();
  685. Dispatcher.Invoke(()=> Refresh(false, false));
  686. });
  687. //StopConsole(key);
  688. }
  689. else if (service.Status == ServiceControllerStatus.Stopped)
  690. {
  691. task = Task.Run(
  692. () =>
  693. {
  694. service.Start();
  695. Dispatcher.Invoke(()=> Refresh(false, false));
  696. });
  697. StartConsole(arg,key);
  698. }
  699. else if (service.Status == ServiceControllerStatus.Paused)
  700. {
  701. task = Task.Run(() =>
  702. {
  703. service.Continue();
  704. Dispatcher.Invoke(()=> Refresh(false, false));
  705. });
  706. }
  707. else
  708. {
  709. MessageBox.Show(string.Format("Invalid Service State ({0})", service.Status.ToString()));
  710. return false;
  711. }
  712. task?.ContinueWith((e) =>
  713. {
  714. if (e.Exception?.InnerException is { } inner)
  715. {
  716. if(inner.InnerException != null)
  717. {
  718. MessageBox.Show(String.Format("Error while running service:\n{0}", inner.InnerException.Message));
  719. }
  720. else
  721. {
  722. MessageBox.Show(String.Format("Error while running service:\n{0}", inner.Message));
  723. }
  724. PRSServiceInstaller.UninstallService(arg.Get<Server, string>(x => x.Key));
  725. Refresh(false, true);
  726. }
  727. }, TaskScheduler.FromCurrentSynchronizationContext());
  728. return true;
  729. }
  730. MessageBox.Show("Cannot find Service - is it installed?");
  731. return false;
  732. }
  733. public void StopAll()
  734. {
  735. foreach (var service in _services.ToArray())
  736. if (service.Status == ServiceControllerStatus.Running)
  737. Task.Run(() => { service.Stop(); });
  738. }
  739. #endregion
  740. #region Server Type Images
  741. private readonly Dictionary<ServerType, BitmapImage> _typeimages = new()
  742. {
  743. { ServerType.Database, Properties.Resources.database.AsBitmapImage() },
  744. { ServerType.GPS, Properties.Resources.gps.AsBitmapImage() },
  745. { ServerType.AutoDiscovery, Properties.Resources.autodiscover.AsBitmapImage() },
  746. { ServerType.Schedule, Properties.Resources.schedule.AsBitmapImage() },
  747. { ServerType.Web, Properties.Resources.web.AsBitmapImage() },
  748. { ServerType.Certificate, Properties.Resources.certificate.AsBitmapImage() }
  749. };
  750. private BitmapImage TypeImage(CoreRow? arg)
  751. {
  752. if (arg == null)
  753. return Properties.Resources.help.AsBitmapImage();
  754. var type = arg.Get<Server, ServerType>(c => c.Type);
  755. return _typeimages[type];
  756. }
  757. private FrameworkElement? TypeToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  758. {
  759. if (arg2 == null)
  760. return null;
  761. return arg1.TextToolTip(string.Format("{0} Service\nName: {1}",
  762. arg2.Get<Server, ServerType>(c => c.Type).ToString(),
  763. arg2.Get<Server, string>(c => c.Key)
  764. ));
  765. }
  766. #endregion
  767. #region Console Functions
  768. private BitmapImage? ConsoleImage(CoreRow? arg)
  769. {
  770. if (arg == null)
  771. return Properties.Resources.target.AsBitmapImage();
  772. var service = GetService(arg.Get<Server, string>(c => c.Key));
  773. var state = service != null ? (int)service.Status : 0;
  774. if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
  775. return Properties.Resources.target.AsBitmapImage();
  776. return null;
  777. }
  778. private bool ConsoleAction(CoreRow? arg)
  779. {
  780. if (arg == null)
  781. return false;
  782. var key = arg.Get<Server, string>(c => c.Key);
  783. var service = GetService(key);
  784. var state = service != null ? (int)service.Status : 0;
  785. if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
  786. StartConsole(arg, key);
  787. return false;
  788. }
  789. private Dictionary<String, Tuple<ServerConsole, int>> _consoles = new Dictionary<string, Tuple<ServerConsole, int>>();
  790. private void StartConsole(CoreRow arg, string key)
  791. {
  792. if (_consoles.ContainsKey(key))
  793. return;
  794. var name = arg.Get<Server, string>(c => c.Name);
  795. var console = new ServerConsole(key, $"{key} - {name}");
  796. var window = Window.GetWindow(this);
  797. int i = 0;
  798. while (_consoles.Any(x => x.Value.Item2 == i))
  799. i++;
  800. _consoles[key] = new Tuple<ServerConsole, int>(console, i);
  801. console.Top = window.Top + (i * 50);
  802. console.Left = window.Left + window.Width + 2 + (i*50);
  803. console.Height = window.Height;
  804. console.Closing += (o, e) =>
  805. {
  806. var c = o as ServerConsole;
  807. if (_consoles.ContainsKey(c.ServiceName))
  808. _consoles.Remove(c.ServiceName);
  809. };
  810. console.Show();
  811. }
  812. private void StopConsole(String key)
  813. {
  814. if (!_consoles.ContainsKey(key))
  815. return;
  816. var console = _consoles[key].Item1;
  817. console.Close();
  818. }
  819. #endregion
  820. #region Individual Server Buttons
  821. // Check if a database server is running at the given url and port
  822. private bool IsDatabaseServerRunning(string url, int port)
  823. {
  824. var uri = new Uri(string.Format("{0}:{1}", url, port));
  825. var cli = new RestClient(uri);
  826. var req = new RestRequest("/classes", Method.Get) { Timeout = 20000 };
  827. try
  828. {
  829. var res = cli.Execute(req);
  830. if (res.StatusCode != HttpStatusCode.OK || res.ErrorException != null)
  831. return false;
  832. return true;
  833. }
  834. catch (Exception e)
  835. {
  836. }
  837. return false;
  838. }
  839. // The following variables keep track of whether a database is currently being used, since if two people try to access two different databases,
  840. // terrible things will ensue.
  841. private int currentServerUsers;
  842. private string? currentServerURL;
  843. private int? currentServerPort;
  844. /// <summary>
  845. /// Configures a server for the duration of an action
  846. /// </summary>
  847. /// <typeparam name="TProperties"></typeparam>
  848. /// <param name="row"></param>
  849. /// <param name="hostaddress"></param>
  850. /// <param name="portnumber"></param>
  851. /// <param name="action"></param>
  852. /// <param name="blocking">
  853. /// If blocking is set to false, then currentServerUsers must be decreased by one manually once the
  854. /// task finishes
  855. /// </param>
  856. private void ConfigureServer<TProperties>(
  857. CoreRow row,
  858. Func<TProperties, string> hostaddress,
  859. Func<TProperties, int> portnumber,
  860. Action action,
  861. bool blocking = true
  862. ) where TProperties : ServerProperties
  863. {
  864. try
  865. {
  866. if (row == null)
  867. throw new Exception("No Row Selected!");
  868. var server = LoadItem(row);
  869. if (server == null)
  870. throw new Exception("Unable to load Server!");
  871. var props = server.Properties as TProperties;
  872. if (props == null)
  873. throw new Exception("Unable to Load Properties!");
  874. var url = hostaddress(props);
  875. var port = portnumber(props);
  876. using (new WaitCursor())
  877. {
  878. if (!IsDatabaseServerRunning(url, port))
  879. throw new Exception("Database Server is not available!");
  880. }
  881. if (action != null)
  882. {
  883. if (currentServerUsers == 0)
  884. {
  885. if (currentServerURL != url || currentServerPort != port)
  886. {
  887. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  888. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  889. }
  890. currentServerURL = url;
  891. currentServerPort = port;
  892. currentServerName = null;
  893. ClientFactory.SetClientType(typeof(RestClient<>), Platform.Server, CoreUtils.GetVersion(), url, port, true);
  894. // override the need to provide credentials when configuring the database
  895. ClientFactory.SetBypass();
  896. }
  897. else
  898. {
  899. if (url != currentServerURL || port != currentServerPort)
  900. throw new Exception(string.Format("A different Database Server ({0}:{1}) is currently in use!", currentServerURL,
  901. currentServerPort));
  902. }
  903. currentServerUsers++;
  904. action();
  905. if (blocking) currentServerUsers--;
  906. }
  907. }
  908. catch (Exception e)
  909. {
  910. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  911. MessageBox.Show(e.Message);
  912. }
  913. }
  914. private string? currentServerName;
  915. private void ConfigureIPCServer<TProperties>(
  916. CoreRow row,
  917. Func<TProperties, string> hostPipeName,
  918. Action action,
  919. bool blocking = true
  920. ) where TProperties : ServerProperties
  921. {
  922. try
  923. {
  924. if (row == null)
  925. throw new Exception("No Row Selected!");
  926. var server = LoadItem(row);
  927. if (server == null)
  928. throw new Exception("Unable to load Server!");
  929. var props = server.Properties as TProperties;
  930. if (props == null)
  931. throw new Exception("Unable to Load Properties!");
  932. var pipeName = DatabaseServerProperties.GetPipeName(hostPipeName(props), false);
  933. if (action != null)
  934. {
  935. if (currentServerUsers == 0)
  936. {
  937. if (currentServerName != pipeName)
  938. {
  939. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  940. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  941. }
  942. currentServerPort = null;
  943. currentServerURL = null;
  944. currentServerName = pipeName;
  945. ClientFactory.SetClientType(typeof(IPCClient<>), Platform.Server, CoreUtils.GetVersion(), pipeName);
  946. using (new WaitCursor())
  947. {
  948. if (!Client.Ping())
  949. {
  950. ClientFactory.ClearClientType();
  951. throw new Exception("Database Server is not available!");
  952. }
  953. }
  954. // override the need to provide credentials when configuring the database
  955. ClientFactory.SetBypass();
  956. }
  957. else
  958. {
  959. if (pipeName != currentServerName)
  960. throw new Exception(string.Format("A different Database Server ({0}) is currently in use!", currentServerName));
  961. }
  962. currentServerUsers++;
  963. try
  964. {
  965. action();
  966. }
  967. finally
  968. {
  969. if (blocking) currentServerUsers--;
  970. }
  971. }
  972. }
  973. catch (Exception e)
  974. {
  975. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  976. MessageBox.Show(e.Message);
  977. }
  978. }
  979. private void ConfigureLocalDatabase(
  980. CoreRow row,
  981. Action action
  982. )
  983. {
  984. try
  985. {
  986. if (row == null)
  987. throw new Exception("No Row Selected!");
  988. var server = LoadItem(row) ?? throw new Exception("Unable to load Server!");
  989. if (server.Properties is not DatabaseServerProperties properties)
  990. throw new Exception("Unable to Load Properties!");
  991. if (!DbFactory.IsProviderSet || DbFactory.Provider is not SQLiteProvider sql || sql.URL != properties.FileName)
  992. {
  993. ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Server, CoreUtils.GetVersion());
  994. Progress.ShowModal("Configuring database", (progress) =>
  995. {
  996. DbFactory.Stores = CoreUtils.TypeList(
  997. AppDomain.CurrentDomain.GetAssemblies(),
  998. myType =>
  999. myType.IsClass
  1000. && !myType.IsAbstract
  1001. && !myType.IsGenericType
  1002. && myType.GetInterfaces().Contains(typeof(IStore))
  1003. ).ToArray();
  1004. DbFactory.Provider = new SQLiteProvider(properties.FileName);
  1005. DbFactory.Start();
  1006. StoreUtils.GoogleAPIKey = properties.GoogleAPIKey;
  1007. PurchaseOrder.PONumberPrefix = properties.PurchaseOrderPrefix;
  1008. Job.JobNumberPrefix = properties.JobPrefix;
  1009. });
  1010. }
  1011. action();
  1012. }
  1013. catch(Exception e)
  1014. {
  1015. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  1016. MessageBox.Show(e.Message);
  1017. }
  1018. }
  1019. private bool UpdateDatabaseLicense(CoreRow selectedrow)
  1020. {
  1021. ConfigureIPCServer<DatabaseServerProperties>(
  1022. selectedrow,
  1023. //x => "http://127.0.0.1",
  1024. //x => x.Port,
  1025. x => selectedrow.Get<Server, string>(x => x.Key),
  1026. () =>
  1027. {
  1028. new LicenseRenewalForm().ShowDialog();
  1029. }
  1030. );
  1031. return false;
  1032. }
  1033. private bool ManageDeletions(CoreRow row)
  1034. {
  1035. ConfigureLocalDatabase(row, () =>
  1036. {
  1037. new DeletionsWindow().ShowDialog();
  1038. });
  1039. return false;
  1040. }
  1041. private bool EditCustomFields(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. () => { new MasterList(typeof(CustomProperty), "Class", null, true).ShowDialog(); }
  1049. );
  1050. return false;
  1051. }
  1052. private bool EditDatabaseScripts(CoreRow selectedrow)
  1053. {
  1054. ConfigureIPCServer<DatabaseServerProperties>(
  1055. selectedrow,
  1056. //x => "http://127.0.0.1",
  1057. //x => x.Port,
  1058. x => selectedrow.Get<Server, string>(x => x.Key),
  1059. () => { new MasterList(typeof(Script), "Section", null, true).ShowDialog(); }
  1060. );
  1061. return false;
  1062. }
  1063. private bool EditScheduledScripts(CoreRow selectedrow)
  1064. {
  1065. ConfigureIPCServer<ScheduleServerProperties>(
  1066. selectedrow,
  1067. x => x.Server,
  1068. () => { new MasterList(typeof(ScheduledScript), "", null, true, typeof(ScheduledScriptsGrid)).ShowDialog(); }
  1069. );
  1070. return false;
  1071. }
  1072. private bool EditWebTemplates(CoreRow selectedRow)
  1073. {
  1074. ConfigureIPCServer<WebServerProperties>(
  1075. selectedRow,
  1076. x => x.Server,
  1077. () =>
  1078. {
  1079. var window = new MasterList(typeof(WebTemplate), "DataModel", "", true);
  1080. window.Closed += (e, args) => { currentServerUsers--; };
  1081. window.Show();
  1082. },
  1083. false
  1084. );
  1085. return false;
  1086. }
  1087. private bool EditWebStyles(CoreRow selectedRow)
  1088. {
  1089. ConfigureIPCServer<WebServerProperties>(
  1090. selectedRow,
  1091. x => x.Server,
  1092. () =>
  1093. {
  1094. var window = new MasterList(typeof(WebStyle), "Code", "", true);
  1095. window.Closed += (e, args) => { currentServerUsers--; };
  1096. window.Show();
  1097. },
  1098. false
  1099. );
  1100. return false;
  1101. }
  1102. private bool EditWebDocuments(CoreRow selectedRow)
  1103. {
  1104. ConfigureIPCServer<WebServerProperties>(
  1105. selectedRow,
  1106. x => x.Server,
  1107. () =>
  1108. {
  1109. var window = new MasterList(typeof(WebDocument), "Code", "", true);
  1110. window.Closed += (e, args) => { currentServerUsers--; };
  1111. window.Show();
  1112. },
  1113. false
  1114. );
  1115. return false;
  1116. }
  1117. private bool PRSMobileSettings(CoreRow selectedrow)
  1118. {
  1119. ConfigureIPCServer<WebServerProperties>(
  1120. selectedrow,
  1121. x => x.Server,
  1122. () =>
  1123. {
  1124. var editor = new DynamicEditorForm(typeof(WebSettings));
  1125. var settings = new GlobalConfiguration<WebSettings>().Load();
  1126. editor.Items = new[] { settings };
  1127. if (editor.ShowDialog() == true) new GlobalConfiguration<WebSettings>().Save(settings);
  1128. }
  1129. );
  1130. return false;
  1131. }
  1132. private bool ShowServiceStatus(Button arg1, CoreRow[] arg2)
  1133. {
  1134. List<String> domains = new List<String>();
  1135. var certservers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) == ServerType.Certificate)
  1136. .Select(row => LoadItem(row));;
  1137. foreach (var certserver in certservers)
  1138. {
  1139. var certprops = certserver.Properties as CertificateEngineProperties;
  1140. if (certprops != null)
  1141. domains.AddRange(certprops.ParseDomainNames());
  1142. }
  1143. if (!domains.Any())
  1144. domains.Add("localhost");
  1145. var servers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) != ServerType.Certificate)
  1146. .Select(row => LoadItem(row));
  1147. var statusgrid = new ServiceStatus(domains, servers);
  1148. statusgrid.ShowDialog();
  1149. return false;
  1150. }
  1151. #endregion
  1152. }