ServerGrid.cs 48 KB

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