ServerGrid.cs 45 KB

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