Console.xaml.cs 13 KB

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