Console.xaml.cs 13 KB

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