ServerGrid.cs 45 KB

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