ServerGrid.cs 49 KB

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