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