ServerGrid.cs 49 KB

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