ServerGrid.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  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.ReadOnly = !enabled;
  634. propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
  635. propertyEditor.Items = new BaseObject[] { item };
  636. return propertyEditor.ShowDialog() == true;
  637. }
  638. #endregion
  639. #region Service Start / Stop Actions
  640. private readonly Dictionary<int, BitmapImage> _stateimages = new()
  641. {
  642. { 0, Properties.Resources.warning.AsBitmapImage() },
  643. { (int)ServiceControllerStatus.Stopped, Properties.Resources.pause.AsBitmapImage() },
  644. { (int)ServiceControllerStatus.StartPending, Properties.Resources.working.AsBitmapImage() },
  645. { (int)ServiceControllerStatus.StopPending, Properties.Resources.working.AsBitmapImage() },
  646. { (int)ServiceControllerStatus.Running, Properties.Resources.tick.AsBitmapImage() },
  647. { (int)ServiceControllerStatus.ContinuePending, Properties.Resources.working.AsBitmapImage() },
  648. { (int)ServiceControllerStatus.PausePending, Properties.Resources.working.AsBitmapImage() },
  649. { (int)ServiceControllerStatus.Paused, Properties.Resources.pause.AsBitmapImage() }
  650. };
  651. private BitmapImage StateImage(CoreRow? arg)
  652. {
  653. if (arg == null)
  654. return Properties.Resources.tick.AsBitmapImage();
  655. var key = arg.Get<Server, string>(c => c.Key);
  656. var service = GetService(key);
  657. int state = service != null ? (int)service.Status : 0;
  658. return _stateimages[state];
  659. }
  660. private FrameworkElement? StateToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  661. {
  662. if (arg2 == null)
  663. return null;
  664. var service = GetService(arg2.Get<Server, string>(c => c.Key));
  665. return arg1.TextToolTip(service != null ? "Current State: " + service.Status : "Not Installed");
  666. }
  667. private FrameworkElement? MenuToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  668. {
  669. return arg2 != null ? arg1.TextToolTip("Server Options") : null;
  670. }
  671. private bool StateAction(CoreRow? arg)
  672. {
  673. if (arg == null)
  674. return false;
  675. var key = arg.Get<Server, string>(c => c.Key);
  676. var service = GetService(arg.Get<Server, string>(c => c.Key));
  677. if (service != null)
  678. {
  679. Task? task;
  680. if (service.Status == ServiceControllerStatus.Running)
  681. {
  682. task = Task.Run(
  683. () =>
  684. {
  685. service.Stop();
  686. Dispatcher.Invoke(()=> Refresh(false, false));
  687. });
  688. //StopConsole(key);
  689. }
  690. else if (service.Status == ServiceControllerStatus.Stopped)
  691. {
  692. task = Task.Run(
  693. () =>
  694. {
  695. service.Start();
  696. Dispatcher.Invoke(()=> Refresh(false, false));
  697. });
  698. StartConsole(arg,key);
  699. }
  700. else if (service.Status == ServiceControllerStatus.Paused)
  701. {
  702. task = Task.Run(() =>
  703. {
  704. service.Continue();
  705. Dispatcher.Invoke(()=> Refresh(false, false));
  706. });
  707. }
  708. else
  709. {
  710. MessageBox.Show(string.Format("Invalid Service State ({0})", service.Status.ToString()));
  711. return false;
  712. }
  713. task?.ContinueWith((e) =>
  714. {
  715. if (e.Exception?.InnerException is { } inner)
  716. {
  717. if(inner.InnerException != null)
  718. {
  719. MessageBox.Show(String.Format("Error while running service:\n{0}", inner.InnerException.Message));
  720. }
  721. else
  722. {
  723. MessageBox.Show(String.Format("Error while running service:\n{0}", inner.Message));
  724. }
  725. PRSServiceInstaller.UninstallService(arg.Get<Server, string>(x => x.Key));
  726. Refresh(false, true);
  727. }
  728. }, TaskScheduler.FromCurrentSynchronizationContext());
  729. return true;
  730. }
  731. MessageBox.Show("Cannot find Service - is it installed?");
  732. return false;
  733. }
  734. public void StopAll()
  735. {
  736. foreach (var service in _services.ToArray())
  737. if (service.Status == ServiceControllerStatus.Running)
  738. Task.Run(() => { service.Stop(); });
  739. }
  740. #endregion
  741. #region Server Type Images
  742. private readonly Dictionary<ServerType, BitmapImage> _typeimages = new()
  743. {
  744. { ServerType.Database, Properties.Resources.database.AsBitmapImage() },
  745. { ServerType.GPS, Properties.Resources.gps.AsBitmapImage() },
  746. { ServerType.AutoDiscovery, Properties.Resources.autodiscover.AsBitmapImage() },
  747. { ServerType.Schedule, Properties.Resources.schedule.AsBitmapImage() },
  748. { ServerType.Web, Properties.Resources.web.AsBitmapImage() },
  749. { ServerType.Certificate, Properties.Resources.certificate.AsBitmapImage() }
  750. };
  751. private BitmapImage TypeImage(CoreRow? arg)
  752. {
  753. if (arg == null)
  754. return Properties.Resources.help.AsBitmapImage();
  755. var type = arg.Get<Server, ServerType>(c => c.Type);
  756. return _typeimages[type];
  757. }
  758. private FrameworkElement? TypeToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  759. {
  760. if (arg2 == null)
  761. return null;
  762. return arg1.TextToolTip(string.Format("{0} Service\nName: {1}",
  763. arg2.Get<Server, ServerType>(c => c.Type).ToString(),
  764. arg2.Get<Server, string>(c => c.Key)
  765. ));
  766. }
  767. #endregion
  768. #region Console Functions
  769. private BitmapImage? ConsoleImage(CoreRow? arg)
  770. {
  771. if (arg == null)
  772. return Properties.Resources.target.AsBitmapImage();
  773. var service = GetService(arg.Get<Server, string>(c => c.Key));
  774. var state = service != null ? (int)service.Status : 0;
  775. if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
  776. return Properties.Resources.target.AsBitmapImage();
  777. return null;
  778. }
  779. private bool ConsoleAction(CoreRow? arg)
  780. {
  781. if (arg == null)
  782. return false;
  783. var key = arg.Get<Server, string>(c => c.Key);
  784. var service = GetService(key);
  785. var state = service != null ? (int)service.Status : 0;
  786. if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
  787. StartConsole(arg, key);
  788. return false;
  789. }
  790. private Dictionary<String, Tuple<ServerConsole, int>> _consoles = new Dictionary<string, Tuple<ServerConsole, int>>();
  791. private void StartConsole(CoreRow arg, string key)
  792. {
  793. if (_consoles.ContainsKey(key))
  794. return;
  795. var name = arg.Get<Server, string>(c => c.Name);
  796. var console = new ServerConsole(key, $"{key} - {name}");
  797. var window = Window.GetWindow(this);
  798. int i = 0;
  799. while (_consoles.Any(x => x.Value.Item2 == i))
  800. i++;
  801. _consoles[key] = new Tuple<ServerConsole, int>(console, i);
  802. console.Top = window.Top + (i * 50);
  803. console.Left = window.Left + window.Width + 2 + (i*50);
  804. console.Height = window.Height;
  805. console.Closing += (o, e) =>
  806. {
  807. var c = o as ServerConsole;
  808. if (_consoles.ContainsKey(c.ServiceName))
  809. _consoles.Remove(c.ServiceName);
  810. };
  811. console.Show();
  812. }
  813. private void StopConsole(String key)
  814. {
  815. if (!_consoles.ContainsKey(key))
  816. return;
  817. var console = _consoles[key].Item1;
  818. console.Close();
  819. }
  820. #endregion
  821. #region Individual Server Buttons
  822. // Check if a database server is running at the given url and port
  823. private bool IsDatabaseServerRunning(string url, int port)
  824. {
  825. var uri = new Uri(string.Format("{0}:{1}", url, port));
  826. var cli = new RestClient(uri);
  827. var req = new RestRequest("/classes", Method.Get) { Timeout = TimeSpan.FromSeconds(20) };
  828. try
  829. {
  830. var res = cli.Execute(req);
  831. if (res.StatusCode != HttpStatusCode.OK || res.ErrorException != null)
  832. return false;
  833. return true;
  834. }
  835. catch (Exception e)
  836. {
  837. }
  838. return false;
  839. }
  840. // The following variables keep track of whether a database is currently being used, since if two people try to access two different databases,
  841. // terrible things will ensue.
  842. private int currentServerUsers;
  843. private string? currentServerURL;
  844. private int? currentServerPort;
  845. /// <summary>
  846. /// Configures a server for the duration of an action
  847. /// </summary>
  848. /// <typeparam name="TProperties"></typeparam>
  849. /// <param name="row"></param>
  850. /// <param name="hostaddress"></param>
  851. /// <param name="portnumber"></param>
  852. /// <param name="action"></param>
  853. /// <param name="blocking">
  854. /// If blocking is set to false, then currentServerUsers must be decreased by one manually once the
  855. /// task finishes
  856. /// </param>
  857. private void ConfigureServer<TProperties>(
  858. CoreRow row,
  859. Func<TProperties, string> hostaddress,
  860. Func<TProperties, int> portnumber,
  861. Action action,
  862. bool blocking = true
  863. ) where TProperties : ServerProperties
  864. {
  865. try
  866. {
  867. if (row == null)
  868. throw new Exception("No Row Selected!");
  869. var server = LoadItem(row);
  870. if (server == null)
  871. throw new Exception("Unable to load Server!");
  872. var props = server.Properties as TProperties;
  873. if (props == null)
  874. throw new Exception("Unable to Load Properties!");
  875. var url = hostaddress(props);
  876. var port = portnumber(props);
  877. using (new WaitCursor())
  878. {
  879. if (!IsDatabaseServerRunning(url, port))
  880. throw new Exception("Database Server is not available!");
  881. }
  882. if (action != null)
  883. {
  884. if (currentServerUsers == 0)
  885. {
  886. if (currentServerURL != url || currentServerPort != port)
  887. {
  888. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  889. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  890. }
  891. currentServerURL = url;
  892. currentServerPort = port;
  893. currentServerName = null;
  894. ClientFactory.SetClientType(typeof(RestClient<>), Platform.Server, CoreUtils.GetVersion(), url, port, true);
  895. // override the need to provide credentials when configuring the database
  896. ClientFactory.SetBypass();
  897. }
  898. else
  899. {
  900. if (url != currentServerURL || port != currentServerPort)
  901. throw new Exception(string.Format("A different Database Server ({0}:{1}) is currently in use!", currentServerURL,
  902. currentServerPort));
  903. }
  904. currentServerUsers++;
  905. action();
  906. if (blocking) currentServerUsers--;
  907. }
  908. }
  909. catch (Exception e)
  910. {
  911. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  912. MessageBox.Show(e.Message);
  913. }
  914. }
  915. private string? currentServerName;
  916. private void ConfigureIPCServer<TProperties>(
  917. CoreRow row,
  918. Func<TProperties, string> hostPipeName,
  919. Action action,
  920. bool blocking = true
  921. ) where TProperties : ServerProperties
  922. {
  923. try
  924. {
  925. if (row == null)
  926. throw new Exception("No Row Selected!");
  927. var server = LoadItem(row);
  928. if (server == null)
  929. throw new Exception("Unable to load Server!");
  930. var props = server.Properties as TProperties;
  931. if (props == null)
  932. throw new Exception("Unable to Load Properties!");
  933. var pipeName = DatabaseServerProperties.GetPipeName(hostPipeName(props), false);
  934. if (action != null)
  935. {
  936. if (currentServerUsers == 0)
  937. {
  938. if (currentServerName != pipeName)
  939. {
  940. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  941. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  942. }
  943. currentServerPort = null;
  944. currentServerURL = null;
  945. currentServerName = pipeName;
  946. ClientFactory.SetClientType(typeof(IPCClient<>), Platform.Server, CoreUtils.GetVersion(), pipeName);
  947. using (new WaitCursor())
  948. {
  949. if (!Client.Ping())
  950. {
  951. ClientFactory.ClearClientType();
  952. throw new Exception("Database Server is not available!");
  953. }
  954. }
  955. // override the need to provide credentials when configuring the database
  956. ClientFactory.SetBypass();
  957. }
  958. else
  959. {
  960. if (pipeName != currentServerName)
  961. throw new Exception(string.Format("A different Database Server ({0}) is currently in use!", currentServerName));
  962. }
  963. currentServerUsers++;
  964. try
  965. {
  966. action();
  967. }
  968. finally
  969. {
  970. if (blocking) currentServerUsers--;
  971. }
  972. }
  973. }
  974. catch (Exception e)
  975. {
  976. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  977. MessageBox.Show(e.Message);
  978. }
  979. }
  980. private void ConfigureLocalDatabase(
  981. CoreRow row,
  982. Action action
  983. )
  984. {
  985. try
  986. {
  987. if (row == null)
  988. throw new Exception("No Row Selected!");
  989. var server = LoadItem(row) ?? throw new Exception("Unable to load Server!");
  990. if (server.Properties is not DatabaseServerProperties properties)
  991. throw new Exception("Unable to Load Properties!");
  992. if (!DbFactory.IsProviderSet || DbFactory.ProviderFactory is not SQLiteProviderFactory sql || sql.URL != properties.FileName)
  993. {
  994. ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Server, CoreUtils.GetVersion());
  995. Progress.ShowModal("Configuring database", (progress) =>
  996. {
  997. DbFactory.Stores = CoreUtils.TypeList(
  998. AppDomain.CurrentDomain.GetAssemblies(),
  999. myType =>
  1000. myType.IsClass
  1001. && !myType.IsAbstract
  1002. && !myType.IsGenericType
  1003. && myType.GetInterfaces().Contains(typeof(IStore))
  1004. ).ToArray();
  1005. DbFactory.DefaultStore = typeof(BaseStore<>);
  1006. DbFactory.ProviderFactory = new SQLiteProviderFactory(properties.FileName);
  1007. DbFactory.Start();
  1008. StoreUtils.GoogleAPIKey = properties.GoogleAPIKey;
  1009. PurchaseOrder.PONumberPrefix = properties.PurchaseOrderPrefix;
  1010. Job.JobNumberPrefix = properties.JobPrefix;
  1011. });
  1012. }
  1013. action();
  1014. }
  1015. catch(Exception e)
  1016. {
  1017. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  1018. MessageBox.Show(e.Message);
  1019. }
  1020. }
  1021. private bool UpdateDatabaseLicense(CoreRow selectedrow)
  1022. {
  1023. ConfigureIPCServer<DatabaseServerProperties>(
  1024. selectedrow,
  1025. //x => "http://127.0.0.1",
  1026. //x => x.Port,
  1027. x => selectedrow.Get<Server, string>(x => x.Key),
  1028. () =>
  1029. {
  1030. new LicenseRenewalForm().ShowDialog();
  1031. }
  1032. );
  1033. return false;
  1034. }
  1035. private bool ManageDeletions(CoreRow row)
  1036. {
  1037. ConfigureLocalDatabase(row, () =>
  1038. {
  1039. new DeletionsWindow().ShowDialog();
  1040. });
  1041. return false;
  1042. }
  1043. private bool EditCustomFields(CoreRow selectedrow)
  1044. {
  1045. ConfigureIPCServer<DatabaseServerProperties>(
  1046. selectedrow,
  1047. //x => "http://127.0.0.1",
  1048. //x => x.Port,
  1049. x => selectedrow.Get<Server, string>(x => x.Key),
  1050. () => { new MasterList(typeof(CustomProperty), "Class", null, true).ShowDialog(); }
  1051. );
  1052. return false;
  1053. }
  1054. private bool EditDatabaseScripts(CoreRow selectedrow)
  1055. {
  1056. ConfigureIPCServer<DatabaseServerProperties>(
  1057. selectedrow,
  1058. //x => "http://127.0.0.1",
  1059. //x => x.Port,
  1060. x => selectedrow.Get<Server, string>(x => x.Key),
  1061. () => { new MasterList(typeof(Script), "Section", null, true).ShowDialog(); }
  1062. );
  1063. return false;
  1064. }
  1065. private bool EditScheduledScripts(CoreRow selectedrow)
  1066. {
  1067. ConfigureIPCServer<ScheduleServerProperties>(
  1068. selectedrow,
  1069. x => x.Server,
  1070. () => { new MasterList(typeof(ScheduledScript), "", null, true, typeof(ScheduledScriptsGrid)).ShowDialog(); }
  1071. );
  1072. return false;
  1073. }
  1074. private bool EditWebTemplates(CoreRow selectedRow)
  1075. {
  1076. ConfigureIPCServer<WebServerProperties>(
  1077. selectedRow,
  1078. x => x.Server,
  1079. () =>
  1080. {
  1081. var window = new MasterList(typeof(WebTemplate), "DataModel", "", true);
  1082. window.Closed += (e, args) => { currentServerUsers--; };
  1083. window.Show();
  1084. },
  1085. false
  1086. );
  1087. return false;
  1088. }
  1089. private bool EditWebStyles(CoreRow selectedRow)
  1090. {
  1091. ConfigureIPCServer<WebServerProperties>(
  1092. selectedRow,
  1093. x => x.Server,
  1094. () =>
  1095. {
  1096. var window = new MasterList(typeof(WebStyle), "Code", "", true);
  1097. window.Closed += (e, args) => { currentServerUsers--; };
  1098. window.Show();
  1099. },
  1100. false
  1101. );
  1102. return false;
  1103. }
  1104. private bool EditWebDocuments(CoreRow selectedRow)
  1105. {
  1106. ConfigureIPCServer<WebServerProperties>(
  1107. selectedRow,
  1108. x => x.Server,
  1109. () =>
  1110. {
  1111. var window = new MasterList(typeof(WebDocument), "Code", "", true);
  1112. window.Closed += (e, args) => { currentServerUsers--; };
  1113. window.Show();
  1114. },
  1115. false
  1116. );
  1117. return false;
  1118. }
  1119. private bool PRSMobileSettings(CoreRow selectedrow)
  1120. {
  1121. ConfigureIPCServer<WebServerProperties>(
  1122. selectedrow,
  1123. x => x.Server,
  1124. () =>
  1125. {
  1126. var editor = new DynamicEditorForm(typeof(WebSettings));
  1127. var settings = new GlobalConfiguration<WebSettings>().Load();
  1128. editor.Items = new[] { settings };
  1129. if (editor.ShowDialog() == true) new GlobalConfiguration<WebSettings>().Save(settings);
  1130. }
  1131. );
  1132. return false;
  1133. }
  1134. private bool ShowServiceStatus(Button arg1, CoreRow[] arg2)
  1135. {
  1136. List<String> domains = new List<String>();
  1137. var certservers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) == ServerType.Certificate)
  1138. .Select(row => LoadItem(row));
  1139. foreach (var certserver in certservers)
  1140. {
  1141. var certprops = certserver.Properties as CertificateEngineProperties;
  1142. if (certprops != null)
  1143. domains.AddRange(certprops.ParseDomainNames());
  1144. }
  1145. if (!domains.Any())
  1146. domains.Add("localhost");
  1147. var servers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) != ServerType.Certificate)
  1148. .Select(row => LoadItem(row));
  1149. var statusgrid = new ServiceStatus(domains, servers);
  1150. statusgrid.ShowDialog();
  1151. return false;
  1152. }
  1153. #endregion
  1154. }