ServerGrid.cs 47 KB

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