ServerGrid.cs 45 KB

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