Console.xaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. using H.Pipes;
  2. using InABox.Core;
  3. using InABox.DynamicGrid;
  4. using InABox.Wpf.Editors;
  5. using InABox.WPF;
  6. using PRSServices;
  7. using System;
  8. using System.ComponentModel;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.CompilerServices;
  12. using System.Threading.Tasks;
  13. using System.Timers;
  14. using System.Windows;
  15. using InABox.Clients;
  16. using InABox.Rpc;
  17. using PRSServer;
  18. using Comal.Classes;
  19. using InABox.Wpf;
  20. using Microsoft.Win32;
  21. using PRS.Shared;
  22. namespace PRSLicensing;
  23. public class LicenseEditData : BaseObject
  24. {
  25. [EditorSequence(1)]
  26. public CustomerLink Customer { get; set; }
  27. [EditorSequence(2)]
  28. public DateTime ExpiryDate { get; set; }
  29. [EditorSequence(3)]
  30. public bool IsDynamic { get; set; }
  31. }
  32. /// <summary>
  33. /// Interaction logic for MainWindow.xaml
  34. /// </summary>
  35. public partial class Console : Window, INotifyPropertyChanged
  36. {
  37. private LicensingConfiguration Settings { get; set; }
  38. private Timer timer;
  39. public event PropertyChangedEventHandler? PropertyChanged;
  40. private bool _isRunning = false;
  41. public bool IsRunning
  42. {
  43. get => _isRunning;
  44. set
  45. {
  46. _isRunning = value;
  47. OnPropertyChanged();
  48. }
  49. }
  50. private bool _isInstalled = false;
  51. public bool IsInstalled
  52. {
  53. get => _isInstalled;
  54. set
  55. {
  56. _isInstalled = value;
  57. OnPropertyChanged();
  58. }
  59. }
  60. private bool _hasDbServer = false;
  61. public bool HasDbServer
  62. {
  63. get => _hasDbServer;
  64. set
  65. {
  66. _hasDbServer = value;
  67. OnPropertyChanged();
  68. }
  69. }
  70. private PipeClient<string>? _client;
  71. private Timer? RefreshTimer;
  72. public Console()
  73. {
  74. InitializeComponent();
  75. LoadSettings();
  76. Progress.DisplayImage = PRSLicensing.Resources.splash_small.AsBitmapImage();
  77. timer = new Timer(2000);
  78. timer.Elapsed += Timer_Elapsed;
  79. timer.AutoReset = true;
  80. timer.Start();
  81. }
  82. private string GetUpdateLocation() => "https://prsdigital.com.au/updates/prs";
  83. private string GetLatestVersion(string location) => Update.GetRemoteFile($"{location}/PreRelease/version.txt").Content;
  84. private string GetReleaseNotes(string location)=> Update.GetRemoteFile($"{location}/Release Notes.txt").Content;
  85. private void Window_Loaded(object sender, RoutedEventArgs e)
  86. {
  87. var isUpdateAvailable = Update.CheckForUpdates(
  88. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, null, null, false, "");
  89. RefreshStatus();
  90. Progress.ShowModal("Registering Classes", progress =>
  91. {
  92. var tasks = new Task[]
  93. {
  94. Task.Run(() => CoreUtils.RegisterClasses()),
  95. Task.Run(() => ComalUtils.RegisterClasses()),
  96. Task.Run(() => DynamicGridUtils.RegisterClasses()),
  97. };
  98. Task.WaitAll(tasks.ToArray());
  99. });
  100. }
  101. private void Timer_Elapsed(object? sender, ElapsedEventArgs e)
  102. {
  103. RefreshStatus();
  104. }
  105. protected override void OnClosing(CancelEventArgs e)
  106. {
  107. base.OnClosing(e);
  108. _client?.DisposeAsync().AsTask().Wait();
  109. _client = null;
  110. RefreshTimer?.Stop();
  111. }
  112. private void RefreshStatus()
  113. {
  114. IsRunning = PRSServiceInstaller.IsRunning(Settings.GetServiceName());
  115. IsInstalled = PRSServiceInstaller.IsInstalled(Settings.GetServiceName());
  116. HasDbServer = !String.IsNullOrWhiteSpace(GetProperties().Server);
  117. if(_client is null)
  118. {
  119. if (IsRunning)
  120. {
  121. CreateClient();
  122. }
  123. }
  124. else if(_client.PipeName != GetPipeName())
  125. {
  126. _client.DisposeAsync().AsTask().Wait();
  127. _client = null;
  128. CreateClient();
  129. }
  130. }
  131. private bool _creatingClient = false;
  132. private void CreateClient()
  133. {
  134. if (_creatingClient) return;
  135. _creatingClient = true;
  136. var client = new PipeClient<string>(GetPipeName(), ".");
  137. client.MessageReceived += (o, args) =>
  138. {
  139. Dispatcher.BeginInvoke(() =>
  140. {
  141. ConsoleControl.LoadLogEntry(args.Message ?? "");
  142. });
  143. };
  144. client.Connected += (o, args) =>
  145. {
  146. Dispatcher.BeginInvoke(() =>
  147. {
  148. ConsoleControl.Enabled = true;
  149. });
  150. };
  151. client.Disconnected += (o, args) =>
  152. {
  153. Dispatcher.BeginInvoke(() =>
  154. {
  155. ConsoleControl.Enabled = false;
  156. });
  157. if (RefreshTimer == null)
  158. {
  159. RefreshTimer = new Timer(1000);
  160. RefreshTimer.Elapsed += RefreshTimer_Elapsed;
  161. }
  162. RefreshTimer.Start();
  163. };
  164. client.ExceptionOccurred += (o, args) =>
  165. {
  166. };
  167. if (!client.IsConnecting)
  168. {
  169. client.ConnectAsync();
  170. }
  171. _client = client;
  172. _creatingClient = false;
  173. }
  174. private void RefreshTimer_Elapsed(object? sender, ElapsedEventArgs e)
  175. {
  176. if (_client is null) return;
  177. if (!_client.IsConnected)
  178. {
  179. if (!_client.IsConnecting)
  180. {
  181. _client.ConnectAsync();
  182. }
  183. }
  184. else
  185. {
  186. RefreshTimer?.Stop();
  187. }
  188. }
  189. private string GetPipeName()
  190. {
  191. return Settings.GetServiceName();
  192. }
  193. private void LoadSettings()
  194. {
  195. Settings = PRSLicensingService.GetConfiguration().Load();
  196. ServiceName.Content = Settings.ServiceName;
  197. }
  198. private void SaveSettings()
  199. {
  200. PRSLicensingService.GetConfiguration().Save(Settings);
  201. }
  202. private void Install()
  203. {
  204. var username = GetProperties().Username;
  205. string? password = null;
  206. if (!string.IsNullOrWhiteSpace(username))
  207. {
  208. var passwordEditor = new PasswordDialog(string.Format("Enter password for {0}", username));
  209. if(passwordEditor.ShowDialog() == true)
  210. {
  211. password = passwordEditor.Password;
  212. }
  213. else
  214. {
  215. password = null;
  216. }
  217. }
  218. else
  219. {
  220. username = null;
  221. }
  222. PRSServiceInstaller.InstallService(
  223. Settings.GetServiceName(),
  224. "PRS Licensing Service",
  225. Settings.ServiceName,
  226. username,
  227. password);
  228. }
  229. private void InstallButton_Click(object sender, RoutedEventArgs e)
  230. {
  231. if (PRSServiceInstaller.IsInstalled(Settings.GetServiceName()))
  232. {
  233. Progress.ShowModal("Uninstalling Service", (progress) =>
  234. {
  235. PRSServiceInstaller.UninstallService(Settings.GetServiceName());
  236. });
  237. }
  238. else
  239. {
  240. Progress.ShowModal("Installing Service", (progress) =>
  241. {
  242. Install();
  243. });
  244. }
  245. RefreshStatus();
  246. }
  247. private void StartButton_Click(object sender, RoutedEventArgs e)
  248. {
  249. if (PRSServiceInstaller.IsRunning(Settings.GetServiceName()))
  250. {
  251. Progress.ShowModal("Stopping Service", (progress) =>
  252. {
  253. PRSServiceInstaller.StopService(Settings.GetServiceName());
  254. });
  255. }
  256. else
  257. {
  258. Progress.ShowModal("Starting Service", (progress) =>
  259. {
  260. PRSServiceInstaller.StartService(Settings.GetServiceName());
  261. });
  262. }
  263. RefreshStatus();
  264. }
  265. private LicensingEngineProperties GetProperties()
  266. {
  267. var properties = Serialization.Deserialize<LicensingEngineProperties>(Settings.Properties) ?? new LicensingEngineProperties();
  268. properties.Name = Settings.ServiceName;
  269. var tokens = CoreUtils.TypeList(x =>x.IsSubclassOf(typeof(LicenseToken)))
  270. .OrderBy(x => x.EntityName().Split('.').Last())
  271. .ToArray();
  272. foreach (var token in tokens)
  273. {
  274. if (!properties.Mappings.Any(x => String.Equals(x.License, token.EntityName())))
  275. properties.Mappings.Add(new LicenseProductMapping() { License = token.EntityName() });
  276. }
  277. return properties;
  278. }
  279. private bool CheckConnection()
  280. {
  281. var properties = GetProperties();
  282. if (!String.IsNullOrWhiteSpace(properties.Server))
  283. {
  284. ClientFactory.SetClientType(
  285. typeof(RpcClient<>),
  286. Platform.LicensingEngine,
  287. CoreUtils.GetVersion(),
  288. new RpcClientPipeTransport(DatabaseServerProperties.GetPipeName(properties.Server, true))
  289. );
  290. if (Client.Ping())
  291. {
  292. ClientFactory.SetBypass();
  293. return true;
  294. }
  295. }
  296. return false;
  297. }
  298. private void EditButton_Click(object sender, RoutedEventArgs e)
  299. {
  300. var grid = new DynamicItemsListGrid<LicensingEngineProperties>();
  301. grid.OnEditorLoaded += (editor, items) =>
  302. {
  303. var control = editor.FindEditor(nameof(LicensingEngineProperties.Mappings)) as ButtonEditorControl;
  304. if (control != null)
  305. {
  306. control.OnClick += (o, args) =>
  307. {
  308. DynamicItemsListGrid<LicenseProductMapping> mappinggrid =
  309. new DynamicItemsListGrid<LicenseProductMapping>();
  310. mappinggrid.Items = items.First().Mappings;
  311. DynamicGridUtils.CreateGridWindow("License Mappings", mappinggrid).ShowDialog();
  312. };
  313. }
  314. };
  315. Settings.CommitChanges();
  316. var properties = GetProperties();
  317. CheckConnection();
  318. if(grid.EditItems(new LicensingEngineProperties[] { properties }))
  319. {
  320. Settings.Properties = Serialization.Serialize(properties);
  321. Settings.ServiceName = properties.Name;
  322. if (Settings.IsChanged())
  323. {
  324. if(Settings.HasOriginalValue(x => x.ServiceName) || properties.HasOriginalValue(x => x.Username))
  325. {
  326. var oldService = LicensingConfiguration.GetServiceName(Settings.GetOriginalValue(x => x.ServiceName));
  327. if (PRSServiceInstaller.IsInstalled(oldService))
  328. {
  329. Progress.ShowModal("Modifying Service", (progress) =>
  330. {
  331. PRSServiceInstaller.UninstallService(oldService);
  332. Install();
  333. });
  334. }
  335. }
  336. SaveSettings();
  337. ServiceName.Content = Settings.ServiceName;
  338. RefreshStatus();
  339. }
  340. }
  341. }
  342. protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
  343. {
  344. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  345. }
  346. private void GenerateButton_Click(object sender, RoutedEventArgs e)
  347. {
  348. if (!CheckConnection())
  349. {
  350. MessageWindow.ShowMessage("Unable to connect to Server", "Error");
  351. return;
  352. }
  353. var ofd = new OpenFileDialog()
  354. {
  355. FileName = "license.request",
  356. Filter = "Request Files (*.request)|*.request"
  357. };
  358. if (ofd.ShowDialog() == true && System.IO.File.Exists(ofd.FileName))
  359. {
  360. var text = System.IO.File.ReadAllText(ofd.FileName);
  361. if (LicenseUtils.TryDecryptLicenseRequest(text, out var request, out var _))
  362. {
  363. var data = new LicenseEditData();
  364. data.Customer.ID = request.CustomerID;
  365. data.IsDynamic = request.IsDynamic;
  366. var grid = new DynamicItemsListGrid<LicenseEditData>();
  367. grid.OnValidate += (o, items, errors) =>
  368. {
  369. if (items.Any(x => x.Customer.ID == Guid.Empty))
  370. errors.Add("Customer may not be blank!");
  371. if (items.Any(x => x.ExpiryDate <= DateTime.Today))
  372. errors.Add("Expiry must be in the future!");
  373. };
  374. if (grid.EditItems(new LicenseEditData[] { data }))
  375. {
  376. var license = new LicenseData()
  377. {
  378. CustomerID = data.Customer.ID,
  379. Expiry = data.ExpiryDate,
  380. RenewalAvailable = data.ExpiryDate.AddMonths(-1),
  381. LastRenewal = DateTime.Today,
  382. Addresses = request.Addresses,
  383. IsDynamic = data.IsDynamic
  384. };
  385. SaveFileDialog sfd = new SaveFileDialog()
  386. {
  387. FileName = "license.key"
  388. };
  389. if (sfd.ShowDialog() == true)
  390. File.WriteAllText(sfd.FileName, LicenseUtils.EncryptLicense(license));
  391. }
  392. }
  393. else
  394. MessageWindow.ShowMessage("Invalid Request File","Error");
  395. }
  396. }
  397. }