ServerGrid.cs 49 KB

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