ServerGrid.cs 47 KB

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