ServerGrid.cs 45 KB

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