From b2a1c830b14a2f9639cc971432df2f906570796a Mon Sep 17 00:00:00 2001 From: Steven Date: Fri, 23 Feb 2024 22:56:05 +0100 Subject: [PATCH] Version 1.8.8819 Version 1.8.8819 ----------------------------------------------------------------- Frontend related changes - Feature: "Checkpoints" now do have a "header number" - Feature: "Checkpoints" now do have a context-menu "copy / paste" - Feature: "Checkpoints" can now be created on the cursor position instead of "only at the end" - Improvement: Auto scroll feature. Scrolling down when a tasklist executes now also keep the most left cell in focus. Backend related changes - ReaderDevice Improvement: Upgraded Elatec.NET to v0.2 in order to utilize async/await - App ID Length limited to 8 digits - Improvement: converted most of the Methods to utilize async/await - Logging: Log to Windows Event Viewer with new Source "RFiDGear" - Installer: Create a new EventSource "RFiDGear" --- .gitignore | 1 + RFiDGear.sln | 50 +- .../RedCell.Diagnostics.Update/Updater.cs | 230 +- RFiDGear/App.xaml | 6 +- RFiDGear/DataAccessLayer/Local/Constants.cs | 301 ++- .../DataAccessLayer/Local/CustomConverter.cs | 2 - .../DataAccessLayer/Local/ResourceLoader.cs | 15 +- .../Remote/FromFile/DatabaseReaderWriter.cs | 163 +- .../Remote/FromFile/ReportReaderWriter.cs | 113 +- .../Remote/FromFile/SettingsReaderWriter.cs | 199 +- .../Remote/FromIO/ElatecNetProvider.cs | 993 +++++--- .../Remote/FromIO/ReaderDevice.cs | 53 +- RFiDGear/Model/Checkpoint.cs | 17 + RFiDGear/Model/GenericChipModel.cs | 27 +- .../MifareClassic/MifareClassicChipModel.cs | 7 + .../MifareDesfire/MifareDesfireChipModel.cs | 31 +- .../MifareUltralightChipModel.cs | 6 + RFiDGear/Properties/AssemblyInfo.cs | 6 +- RFiDGear/RFiDGear.csproj | 14 +- RFiDGear/RFiDGear.csproj.user | 6 +- RFiDGear/Resources/Manifest.de.resx | 152 +- RFiDGear/Resources/Manifest.en.resx | 152 +- RFiDGear/View/MainWindow.xaml | 67 +- .../TabPageMiscReaderSettingsView.xaml | 2 +- .../TaskViews/CommonTask/CommonTaskView.xaml | 2 +- .../TabPageLogicTaskView.xaml | 35 +- .../TabPageReportSettingsView.xaml | 45 +- .../TabPageBasicChipCheckUpView.xaml | 2 +- .../GenericChipTask/GenericChipTaskView.xaml | 2 +- .../MifareDesfireSetupView.xaml | 2 +- RFiDGear/ViewModel/AboutViewModel.cs | 2 +- .../RFiDChipChildLayerViewModel.cs | 79 +- .../RFiDChipGrandChildLayerViewModel.cs | 2 +- .../RFiDChipParentLayerViewModel.cs | 409 ++-- RFiDGear/ViewModel/MainWindowViewModel.cs | 1569 +++++++------ RFiDGear/ViewModel/SetupViewModel.cs | 111 +- RFiDGear/ViewModel/SplashScreenViewModel.cs | 2 +- .../CommonTaskViewModel.cs | 1092 +++++---- .../GenericChipTaskViewModel.cs | 327 ++- .../MifareClassicSetupViewModel.cs | 507 ++-- .../MifareDesfireSetupViewModel.cs | 2030 ++++++++--------- .../MifareUltralightSetupViewModel.cs | 18 +- RFiDGear/ViewModel/UpdateNotifierViewModel.cs | 2 +- RFiDGear/app.config | 60 +- Setup/Product.wxs | 29 +- debugParam.txt | 1 + 46 files changed, 5134 insertions(+), 3807 deletions(-) create mode 100644 debugParam.txt diff --git a/.gitignore b/.gitignore index b6ce1cc..a416e0c 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ *.xml *.zip *.htm +RFiDGear/RFiDGear.SDKStyle.csproj diff --git a/RFiDGear.sln b/RFiDGear.sln index 0366dd6..8d10ff7 100644 --- a/RFiDGear.sln +++ b/RFiDGear.sln @@ -10,18 +10,18 @@ EndProject Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "RFiDGearBundleSetup", "RFiDGearBundleSetup\RFiDGearBundleSetup.wixproj", "{5A7DF993-C696-4958-B7C9-9396122DFF21}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ByteArray", "..\ByteArray\ByteArray.csproj", "{BDD5DF8C-6FC1-4882-8151-924820FDBC05}" - ProjectSection(ProjectDependencies) = postProject - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70} = {786D71E7-4D92-43E4-A9EB-4E07FFE36F70} - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Elatec.NET", "..\Elatec.NET\Elatec.NET.csproj", "{53FBD2F3-638E-4892-9F09-9A372C8F76D2}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Log4CSharp", "..\Log4CSharp\Log4CSharp.csproj", "{786D71E7-4D92-43E4-A9EB-4E07FFE36F70}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PluginSystem", "..\PluginSystem\PluginSystem.csproj", "{E99B606A-25B8-4113-9E75-5016CCFDB410}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MVVMDialogs", "..\MVVMDialogs\MVVMDialogs.csproj", "{EF56252E-257F-41D1-974B-C9015071CE7E}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Elatec.NET", "..\Elatec.NET\Elatec.NET.csproj", "{360F9AF9-6717-45B6-9707-5974575FE96A}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Projektmappenelemente", "Projektmappenelemente", "{A50839AB-9B8F-49C6-AB4A-7BD1BC9FA9DB}" + ProjectSection(SolutionItems) = preProject + debugParam.txt = debugParam.txt + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -72,30 +72,6 @@ Global {BDD5DF8C-6FC1-4882-8151-924820FDBC05}.Release|x64.Build.0 = Release|x64 {BDD5DF8C-6FC1-4882-8151-924820FDBC05}.Release|x86.ActiveCfg = Release|Any CPU {BDD5DF8C-6FC1-4882-8151-924820FDBC05}.Release|x86.Build.0 = Release|Any CPU - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Debug|x64.ActiveCfg = Debug|x64 - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Debug|x64.Build.0 = Debug|x64 - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Debug|x86.ActiveCfg = Debug|x86 - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Debug|x86.Build.0 = Debug|x86 - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Release|Any CPU.Build.0 = Release|Any CPU - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Release|x64.ActiveCfg = Release|x64 - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Release|x64.Build.0 = Release|x64 - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Release|x86.ActiveCfg = Release|x86 - {53FBD2F3-638E-4892-9F09-9A372C8F76D2}.Release|x86.Build.0 = Release|x86 - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Debug|Any CPU.Build.0 = Debug|Any CPU - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Debug|x64.ActiveCfg = Debug|x64 - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Debug|x64.Build.0 = Debug|x64 - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Debug|x86.ActiveCfg = Debug|x86 - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Debug|x86.Build.0 = Debug|x86 - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Release|Any CPU.ActiveCfg = Release|Any CPU - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Release|Any CPU.Build.0 = Release|Any CPU - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Release|x64.ActiveCfg = Release|x64 - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Release|x64.Build.0 = Release|x64 - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Release|x86.ActiveCfg = Release|x86 - {786D71E7-4D92-43E4-A9EB-4E07FFE36F70}.Release|x86.Build.0 = Release|x86 {E99B606A-25B8-4113-9E75-5016CCFDB410}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E99B606A-25B8-4113-9E75-5016CCFDB410}.Debug|Any CPU.Build.0 = Debug|Any CPU {E99B606A-25B8-4113-9E75-5016CCFDB410}.Debug|x64.ActiveCfg = Debug|x64 @@ -120,6 +96,18 @@ Global {EF56252E-257F-41D1-974B-C9015071CE7E}.Release|x64.Build.0 = Release|x64 {EF56252E-257F-41D1-974B-C9015071CE7E}.Release|x86.ActiveCfg = Release|Any CPU {EF56252E-257F-41D1-974B-C9015071CE7E}.Release|x86.Build.0 = Release|Any CPU + {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x64.ActiveCfg = Debug|x64 + {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x64.Build.0 = Debug|x64 + {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x86.ActiveCfg = Debug|x86 + {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x86.Build.0 = Debug|x86 + {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|Any CPU.Build.0 = Release|Any CPU + {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x64.ActiveCfg = Release|x64 + {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x64.Build.0 = Release|x64 + {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x86.ActiveCfg = Release|x86 + {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/RFiDGear/3rdParty/RedCell/RedCell.Diagnostics.Update/Updater.cs b/RFiDGear/3rdParty/RedCell/RedCell.Diagnostics.Update/Updater.cs index 87b8538..308e25b 100644 --- a/RFiDGear/3rdParty/RedCell/RedCell.Diagnostics.Update/Updater.cs +++ b/RFiDGear/3rdParty/RedCell/RedCell.Diagnostics.Update/Updater.cs @@ -1,23 +1,26 @@ using RFiDGear; using RFiDGear.DataAccessLayer; -using Log4CSharp; +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.IO; +using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; +using System.Threading.Tasks; using Ionic.Zip; using RedCell.Net; +using System.Windows.Threading; namespace RedCell.Diagnostics.Update { public class Updater : IDisposable { #region Constants - private static readonly string FacilityName = "RFiDGear"; + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private static readonly string appDataPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @@ -33,13 +36,12 @@ public class Updater : IDisposable /// The default configuration file /// public static readonly string DefaultConfigFile = "update.xml"; - public static readonly string WorkPath = "work"; #endregion #region Fields //private readonly SettingsReaderWriter settings; - private Timer _timer; + private DispatcherTimer _timer; private volatile bool _updating; private readonly Manifest _localConfig; private Manifest _remoteConfig; @@ -49,17 +51,12 @@ public class Updater : IDisposable private readonly string me; public bool AllowUpdate { get; set; } + public bool UpdateAvailable { get; set; } public bool IsUserNotified { get; set; } public string UpdateInfoText { get; private set; } #endregion - #region events - - public event EventHandler NewVersionAvailable; - - #endregion - #region Initialization /// /// Initializes a new instance of the class. @@ -79,11 +76,11 @@ public Updater(FileInfo configFile) { me = thisprocess.MainModule.FileName; - Log.Write("Loaded."); - Log.Write("Initializing using file '{0}'.", configFile.FullName); + eventLog.WriteEntry(string.Format("Loaded"), EventLogEntryType.Information); + eventLog.WriteEntry(string.Format("Initializing using file '{0}'.", configFile), EventLogEntryType.Information); if (!configFile.Exists) { - Log.Write("Config file '{0}' does not exist, stopping.", configFile.Name); + eventLog.WriteEntry(string.Format("Config file '{0}' does not exist, stopping.", configFile), EventLogEntryType.Warning); return; } @@ -99,8 +96,7 @@ public Updater(FileInfo configFile) catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); - + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } #endregion @@ -109,63 +105,80 @@ public Updater(FileInfo configFile) /// /// Starts the monitoring. /// - public void StartMonitoring() + public async Task StartMonitoring() { - if (_localConfig != null) + await Task.Run(() => { - Log.Write("Starting monitoring every {0}s.", _localConfig.CheckInterval); - Check(null); + if (_localConfig != null) + { + eventLog.WriteEntry(string.Format("Starting monitoring every {0}s.", _localConfig.CheckInterval), EventLogEntryType.Information); + Check(null, null); - _timer = new Timer(Check, null, 5000, _localConfig.CheckInterval * 1000); - } + _timer = new DispatcherTimer + { + Interval = new TimeSpan(0, 0, 0, _localConfig.CheckInterval, 0) + }; + + _timer.Tick += Check; + + _timer.Start(); + _timer.IsEnabled = true; + } + }).ConfigureAwait(false); + return; } /// /// Stops the monitoring. /// - public void StopMonitoring() + public async Task StopMonitoring() { - Log.Write("Stopping monitoring."); - if (_timer == null) + await Task.Run(() => { - Log.Write("Monitoring was already stopped."); - return; - } - _timer.Dispose(); + eventLog.WriteEntry(string.Format("Stopping monitoring."), EventLogEntryType.Information); + if (_timer == null) + { + eventLog.WriteEntry(string.Format("Monitoring was already stopped."), EventLogEntryType.Information); + return; + } + _timer.Stop(); + }).ConfigureAwait(false); + + return; } /// /// Checks the specified state. /// /// The state. - private void Check(object state) + public async void Check(object state, EventArgs args) { try { if (AllowUpdate && !_updating) { - _timer.Change(5000, DefaultCheckInterval * 1000); + _timer.Interval = new TimeSpan(0, 0, 0, _localConfig.CheckInterval, 0); _updating = true; - Update(); + await Update(); _updating = false; IsUserNotified = false; - Log.Write("Check ending."); + eventLog.WriteEntry(string.Format("Check ending."), EventLogEntryType.Information); return; } - Log.Write("Check starting."); + eventLog.WriteEntry(string.Format("Check starting."), EventLogEntryType.Information); if (_updating) { - Log.Write("Updater is already updating."); - Log.Write("Check ending."); + eventLog.WriteEntry(string.Format("Updater is already updating."), EventLogEntryType.Warning); + eventLog.WriteEntry(string.Format("Check ending."), EventLogEntryType.Information); return; } var remoteUri = new Uri(_localConfig.RemoteConfigUri); - Log.Write("Fetching '{0}'.", remoteUri.AbsoluteUri); + eventLog.WriteEntry(string.Format("Fetching '{0}'.", _localConfig.RemoteConfigUri), EventLogEntryType.Information); var http = new Fetch { Retries = 5, RetrySleep = 30000, Timeout = 30000 }; try { @@ -173,15 +186,17 @@ private void Check(object state) if (!http.Success) { + try { - Log.Write("Fetch error: {0}", http.Response != null ? http.Response.StatusDescription : ""); + eventLog.WriteEntry(string.Format("Fetch error: {0}", http.Response != null ? http.Response.StatusDescription : ""), EventLogEntryType.Error); } catch { - Log.Write("Fetch error: Unknown http Err"); + eventLog.WriteEntry(string.Format("Fetch error: Unknown http Err"), EventLogEntryType.Information); } + _remoteConfig = null; return; } @@ -189,9 +204,8 @@ private void Check(object state) catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); _remoteConfig = null; - + UpdateAvailable = false; return; } @@ -200,126 +214,130 @@ private void Check(object state) if (_remoteConfig == null) { + UpdateAvailable = false; return; } if (_localConfig.SecurityToken != _remoteConfig.SecurityToken) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}", DateTime.Now, "Security token mismatch."), FacilityName); + UpdateAvailable = false; return; } - LogWriter.CreateLogEntry(string.Format("{0}: {1}", DateTime.Now, "Remote config is valid."), FacilityName); - LogWriter.CreateLogEntry(string.Format("{0}: {1}, {2}", DateTime.Now, "Local version is ", _localConfig.Version), FacilityName); - LogWriter.CreateLogEntry(string.Format("{0}: {1}, {2}", DateTime.Now, "Remote version is ", _remoteConfig.Version), FacilityName); + eventLog.WriteEntry(string.Format("Remote config is valid."), EventLogEntryType.Information); + eventLog.WriteEntry(string.Format("Local version is ", _localConfig.Version), EventLogEntryType.Information); + eventLog.WriteEntry(string.Format("Remote version is ", _remoteConfig.Version), EventLogEntryType.Information); if (_remoteConfig.Version == _localConfig.Version) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}", DateTime.Now, "Versions are the same. Check ending."), FacilityName); + eventLog.WriteEntry(string.Format("Versions are the same. Check ending."), EventLogEntryType.Information); + UpdateAvailable = false; return; } if (_remoteConfig.Version < _localConfig.Version) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}", DateTime.Now, "Remote version is older. That's weird. Check ending."), FacilityName); + eventLog.WriteEntry(string.Format("Remote version is older. That's weird o_O. Check ending."), EventLogEntryType.Warning); + UpdateAvailable = false; return; } - LogWriter.CreateLogEntry(string.Format("{0}: {1}", DateTime.Now, "Remote version is newer. Updating."), FacilityName); - _timer.Change(0, 1000); + eventLog.WriteEntry(string.Format("Remote version is newer. Updating."), EventLogEntryType.Information); + UpdateAvailable = true; + /* + if (_timer != null) + { + _timer.Change(0, 1000); + } + */ if (!AllowUpdate && !IsUserNotified) { IsUserNotified = true; UpdateInfoText = _remoteConfig.VersionInfoText; - NewVersionAvailable(this, null); return; } if (IsUserNotified && !AllowUpdate) { - StopMonitoring(); + await StopMonitoring(); return; } } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } /// /// Updates this instance. /// - public void Update() + public async Task Update() { + UpdateAvailable = true; - Log.Write("Updating '{0}' files.", _remoteConfig.Payloads.Length); - - // Clean up failed attempts. - if (Directory.Exists(Path.Combine(appDataPath, WorkPath))) + await Task.Run(() => { - Log.Write("WARNING: Work directory already exists."); - try { Directory.Delete(Path.Combine(appDataPath, WorkPath), true); } - catch (IOException e) + // Clean up failed attempts. + if (Directory.Exists(Path.Combine(appDataPath, WorkPath))) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); - - return; + //"WARNING: Work directory already exists." + try { Directory.Delete(Path.Combine(appDataPath, WorkPath), true); } + catch + { + return; + } } - } - else - { - try - { - Directory.CreateDirectory(Path.Combine(appDataPath, WorkPath)); - } - catch (Exception e) + else { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); - - return; + try + { + Directory.CreateDirectory(Path.Combine(appDataPath, WorkPath)); + } + catch + { + return; + } } - } - // Download files in manifest. - foreach (var update in _remoteConfig.Payloads) - { - Log.Write("Fetching '{0}'.", update); - var url = _remoteConfig.BaseUri + update; //TODO: make this localizable ? e.g. + (settings.DefaultSpecification.DefaultLanguage == "german" ? "de-de/" : "en-us/") - var file = Fetch.Get(url); - if (file == null) + // Download files in manifest. + foreach (var update in _remoteConfig.Payloads) { - Log.Write("Fetch failed."); - return; - } - var info = new FileInfo(Path.Combine(Path.Combine(appDataPath, WorkPath), update)); - Directory.CreateDirectory(info.DirectoryName); - File.WriteAllBytes(Path.Combine(Path.Combine(appDataPath, WorkPath), update), file); + eventLog.WriteEntry(string.Format("Fetching '{0}'.", update), EventLogEntryType.Information); + var url = _remoteConfig.BaseUri + update; //TODO: make this localizable ? e.g. + (settings.DefaultSpecification.DefaultLanguage == "german" ? "de-de/" : "en-us/") + var file = Fetch.Get(url); + if (file == null) + { + eventLog.WriteEntry(string.Format("Fetch failed."), EventLogEntryType.Error); + return; + } + var info = new FileInfo(Path.Combine(Path.Combine(appDataPath, WorkPath), update)); + Directory.CreateDirectory(info.DirectoryName); + File.WriteAllBytes(Path.Combine(Path.Combine(appDataPath, WorkPath), update), file); - // Unzip - if (Regex.IsMatch(update, @"\.zip")) - { - try + // Unzip + if (Regex.IsMatch(update, @"\.zip")) { - var zipfile = Path.Combine(Path.Combine(appDataPath, WorkPath), update); - using (var zip = ZipFile.Read(zipfile)) + try { - zip.ExtractAll(Path.Combine(appDataPath, WorkPath), ExtractExistingFileAction.Throw); - } + var zipfile = Path.Combine(Path.Combine(appDataPath, WorkPath), update); + using (var zip = ZipFile.Read(zipfile)) + { + zip.ExtractAll(Path.Combine(appDataPath, WorkPath), ExtractExistingFileAction.Throw); + } - File.Delete(zipfile); + File.Delete(zipfile); - AllowUpdate = true; - } - catch (Exception e) - { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); - - return; + AllowUpdate = true; + } + catch + { + return; + } } } - } + }).ConfigureAwait(false); if (IsUserNotified && AllowUpdate) { @@ -342,10 +360,8 @@ public void Update() Environment.Exit(0); } - catch (Exception e) + catch { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); - return; } } diff --git a/RFiDGear/App.xaml b/RFiDGear/App.xaml index e83caf7..2dc9e06 100644 --- a/RFiDGear/App.xaml +++ b/RFiDGear/App.xaml @@ -4,12 +4,12 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006" - xmlns:dialogsview="clr-namespace:MvvmDialogs.View;assembly=MVVMDialogs" - xmlns:dialogsvm="clr-namespace:MvvmDialogs.ViewModels;assembly=MVVMDialogs" + xmlns:dialogsview="clr-namespace:MVVMDialogs.View;assembly=MVVMDialogs" + xmlns:dialogsvm="clr-namespace:MVVMDialogs.ViewModels;assembly=MVVMDialogs" xmlns:local="clr-namespace:RFiDGear" xmlns:mainview="clr-namespace:RFiDGear.View" xmlns:mainvm="clr-namespace:MefMvvm.SharedContracts.ViewModel;assembly=PluginSystem" - xmlns:pre="clr-namespace:MvvmDialogs.Presenters;assembly=MVVMDialogs" + xmlns:pre="clr-namespace:MVVMDialogs.Presenters;assembly=MVVMDialogs" xmlns:vm="clr-namespace:RFiDGear.ViewModel" d1p1:Ignorable="d" StartupUri="View/MainWindow.xaml"> diff --git a/RFiDGear/DataAccessLayer/Local/Constants.cs b/RFiDGear/DataAccessLayer/Local/Constants.cs index ddc4305..8045688 100644 --- a/RFiDGear/DataAccessLayer/Local/Constants.cs +++ b/RFiDGear/DataAccessLayer/Local/Constants.cs @@ -195,8 +195,26 @@ public enum AccessCondition_MifareClassicSectorTrailer } /// - /// Currently Available Cardtechnologies + /// Type of Chip from NXP AN10833 /// + /// + /// + /// Mifare Classic = 0x10xx - 0x1Fxx + /// NXP SAM = 0x20xx - 0x2Fxx + /// Mifare Plus = 0x30xx - 0x3Fxx + /// Mifare Desfire = 0x40xx - 0x7Fxx + /// Desfire Light = 0x80xx - 0x8Fxx + /// Mifare Ultralight = 0x90xx - 0x9Fxx + /// Mifare Mini = 0xA0xx - 0xAFxx + /// NXP NTAG = 0xB0xx - 0xBFxx + /// NXP ICODE = 0xC0xx - 0xCFxx + /// + /// 0bxxxx 0000 = nxp type + /// 0b0000 xxxx = nxp subtype + /// 0bxxxx 1xxx = smartmx variant + /// + /// + [Flags] public enum CARD_TYPE { NOTAG = 0, @@ -241,60 +259,233 @@ public enum CARD_TYPE TOPAZ = 0x89, // "Topaz" CTS = 0x8A, // "CTS256 / CTS512" BLELC = 0x8B, // "Bluetooth Low Energy LEGIC Connect" - // Custom - Unspecified = 0xB0, - NTAG = 0xB1, - MifareMini = 0xB2, - Mifare1K = 0xB3, - Mifare2K = 0xB4, - Mifare4K = 0xB5, - SAM_AV1 = 0xB6, - SAM_AV2 = 0xB7, - MifarePlus_SL0_1K = 0xB9, - MifarePlus_SL0_2K = 0xBA, - MifarePlus_SL0_4K = 0xBB, - MifarePlus_SL1_1K = 0xBC, - MifarePlus_SL1_2K = 0xBD, - MifarePlus_SL1_4K = 0xBE, - MifarePlus_SL2_1K = 0xBF, - MifarePlus_SL2_2K = 0xC0, - MifarePlus_SL2_4K = 0xC1, - MifarePlus_SL3_1K = 0xC2, - MifarePlus_SL3_2K = 0xC3, - MifarePlus_SL3_4K = 0xC4, - DESFire = 0xC5, - DESFireEV1 = 0xC6, - DESFireEV2 = 0xC7, - DESFireEV3 = 0xC8, - SmartMX_DESFire_Generic = 0xC9, - SmartMX_DESFire_2K = 0xCA, - SmartMX_DESFire_4K = 0xCB, - SmartMX_DESFire_8K = 0xCC, - SmartMX_DESFire_16K = 0xCD, - SmartMX_DESFire_32K = 0xCE, - DESFire_256 = 0xD0, - DESFire_2K = 0xD1, - DESFire_4K = 0xD2, - DESFireEV1_256 = 0xD3, - DESFireEV1_2K = 0xD4, - DESFireEV1_4K = 0xD5, - DESFireEV1_8K = 0xD6, - DESFireEV2_2K = 0xD7, - DESFireEV2_4K = 0xD8, - DESFireEV2_8K = 0xD9, - DESFireEV2_16K = 0xDA, - DESFireEV2_32K = 0xDB, - DESFireEV3_2K = 0xDC, - DESFireEV3_4K = 0xDD, - DESFireEV3_8K = 0xDE, - DESFireEV3_16K = 0xDF, - DESFireEV3_32K = 0xE0, - DESFireLight = 0xE1, - SmartMX_Mifare_1K = 0xF9, - SmartMX_Mifare_4K = 0xFA, - MifareUltralight = 0xFB, - MifareUltralightC = 0xFC, - GENERIC_T_CL_A = 0xFF + + /* CUSTOM + * + * Mifare Classic = 0x10 - 0x1F + * NXP SAM = 0x20 - 0x2F + * Mifare Plus = 0x30 - 0x3F + * Mifare Desfire = 0x40 - 0x7F + * Mifare Desfire Light = 0x80 - 0x8F + * Mifare Ultralight = 0x90 - 0x9F + * Mifare Mini = 0xA0 - 0xAF + * NXP NTAG = 0xB0 - 0xBF + * NXP ICODE = 0xC0 - 0xCF + * + * 0bxxxx 0000 = mifare type + * 0x0000 xxxx = mifare subtype + */ + + /* + * 0b0001 xxxx = mifare classic + * 0b0001 1xxx = smartmx classic + * + * 0b0001 0000 = mifare classic - 1k + * 0b0001 0001 = mifare classic - 2k + * 0b0001 0010 = mifare classic - 4k + * + * 0b0001 1000 = smartmx classic - 1k + * 0b0001 1001 = smartmx classic - 2k + * 0b0001 1010 = smartmx classic - 4k + */ + Unspecified = 0x0100, + + MifareClassic = 0x1000, + Mifare1K = 0x1100, + Mifare2K = 0x1200, + Mifare4K = 0x1300, + + SmartMX_Mifare_1K = 0x1900, + SmartMX_Mifare_2K = 0x1A00, + SmartMX_Mifare_4K = 0x1B00, + + /* 0b0010 0000 = MifareSAM + * + * 0b0010 0001 = SAM_AV1 + * 0b0010 0010 = SAM_AV2 + */ + + MifareSAM = 0x2000, + SAM_AV1 = 0x2100, + SAM_AV2 = 0x2200, + + /* 0b0011 xxxx = Mifare Plus + * + * 0b0011 00xx = Mifare Plus SL0 + * 0b0011 0000 = Mifare Plus SL0 - 1k + * 0b0011 0001 = Mifare Plus SL0 - 2k + * 0b0011 0010 = Mifare Plus SL0 - 4k + * + * 0b0011 01xx = Mifare Plus SL1 + * 0b0011 0100 = Mifare Plus SL1 - 1k + * 0b0011 0101 = Mifare Plus SL1 - 2k + * 0b0011 0110 = Mifare Plus SL1 - 4k + * + * 0b0011 10xx = Mifare Plus SL2 + * 0b0011 1000 = Mifare Plus SL2 - 1k + * 0b0011 1001 = Mifare Plus SL2 - 2k + * 0b0011 1010 = Mifare Plus SL2 - 4k + * + * 0b0011 11xx = Mifare Plus SL3 + * 0b0011 1100 = Mifare Plus SL3 - 1k + * 0b0011 1101 = Mifare Plus SL3 - 2k + * 0b0011 1110 = Mifare Plus SL3 - 4k + */ + + MifarePlus = 0x3000, + MifarePlus_SL0_1K = 0x3100, + MifarePlus_SL0_2K = 0x3200, + MifarePlus_SL0_4K = 0x3300, + + MifarePlus_SL1_1K = 0x3400, + MifarePlus_SL1_2K = 0x3500, + MifarePlus_SL1_4K = 0x3600, + + MifarePlus_SL2_1K = 0x3800, + MifarePlus_SL2_2K = 0x3900, + MifarePlus_SL2_4K = 0x3A00, + + MifarePlus_SL3_1K = 0x3C00, + MifarePlus_SL3_2K = 0x3D00, + MifarePlus_SL3_4K = 0x3E00, + + /* 0b01xx xxxx = Mifare Desfire + * 0b01xx 1xxx = SmartMX Desfire + * 0b0100 x000 = EV0 + * 0b0101 x000 = EV1 + * 0b0110 x000 = EV2 + * 0b0111 x000 = EV3 + * + * 0b0100 0001 = Mifare Desfire EV0 - 256 + * 0b0100 0010 = Mifare Desfire EV0 - 1k + * 0b0100 0011 = Mifare Desfire EV0 - 2k + * 0b0100 0100 = Mifare Desfire EV0 - 4k + * + * 0b0100 1xxx = SmartMX Desfire EV0 + * 0b0100 1001 = SmartMX Desfire EV0 - 256 + * 0b0100 1010 = SmartMX Desfire EV0 - 1k + * 0b0100 1011 = SmartMX Desfire EV0 - 2k + * 0b0100 1100 = SmartMX Desfire EV0 - 4k + * + * 0b0101 0xxx = Mifare Desfire EV1 + * 0b0101 0000 = Mifare Desfire EV1 - 256 + * 0b0101 0001 = Mifare Desfire EV1 - 2k + * 0b0101 0010 = Mifare Desfire EV1 - 4k + * 0b0101 0011 = Mifare Desfire EV1 - 8k + * + * 0b0101 1xxx = SmartMX Desfire EV1 + * 0b0101 1000 = SmartMX Desfire EV1 - 256 + * 0b0101 1001 = SmartMX Desfire EV1 - 2k + * 0b0101 1010 = SmartMX Desfire EV1 - 4k + * 0b0101 1011 = SmartMX Desfire EV1 - 8k + * + * 0b0110 0xxx = Mifare Desfire EV2 + * 0b0110 0000 = Mifare Desfire EV2 - 2k + * 0b0110 0001 = Mifare Desfire EV2 - 4k + * 0b0110 0010 = Mifare Desfire EV2 - 8k + * 0b0110 0011 = Mifare Desfire EV2 - 16k + * 0b0110 0100 = Mifare Desfire EV2 - 32k + * + * 0b0110 1xxx = SmartMX Desfire EV2 + * 0b0110 1000 = SmartMX Desfire EV2 - 2k + * 0b0110 1001 = SmartMX Desfire EV2 - 4k + * 0b0110 1010 = SmartMX Desfire EV2 - 8k + * 0b0110 1011 = SmartMX Desfire EV2 - 16k + * 0b0110 1100 = SmartMX Desfire EV2 - 32k + * + * 0b0111 0xxx = Mifare Desfire EV3 + * 0b0111 0000 = Mifare Desfire EV3 - 2k + * 0b0111 0001 = Mifare Desfire EV3 - 4k + * 0b0111 0010 = Mifare Desfire EV3 - 8k + * 0b0111 0011 = Mifare Desfire EV3 - 16k + * 0b0111 0100 = Mifare Desfire EV3 - 32k + * + * 0b0111 1xxx = SmartMX Desfire EV3 + * 0b0111 1000 = SmartMX Desfire EV3 - 1k + * 0b0111 1001 = SmartMX Desfire EV3 - 2k + * 0b0111 1010 = SmartMX Desfire EV3 - 4k + * 0b0111 1011 = SmartMX Desfire EV3 - 16k + * 0b0111 1100 = SmartMX Desfire EV3 - 32k + * + */ + + DESFire = 0x4000, + DESFireEV0 = 0x4000, + DESFireEV0_256 = 0x4100, + DESFireEV0_1K = 0x4200, + DESFireEV0_2K = 0x4300, + DESFireEV0_4K = 0x4400, + // 0x44 - 0x47 = RFU + + SmartMX_DESFire = 0x4800, + SmartMX_DESFire_Generic = 0x4800, + SmartMX_DESFireEV0_256 = 0x4900, + SmartMX_DESFireEV0_1K = 0x4A00, + SmartMX_DESFireEV0_2K = 0x4B00, + SmartMX_DESFireEV0_4K = 0x4C00, + // 0x4C - 0x4F = RFU + + DESFireEV1 = 0x5000, + DESFireEV1_256 = 0x5100, + DESFireEV1_2K = 0x5200, + DESFireEV1_4K = 0x5300, + DESFireEV1_8K = 0x5400, + // 0x55 - 0x57 = RFU + + SmartMX_DESFireEV1_256 = 0x5900, + SmartMX_DESFireEV1_2K = 0x5A00, + SmartMX_DESFireEV1_4K = 0x5B00, + SmartMX_DESFireEV1_8K = 0x5C00, + // 0x5C - 0x5F = RFU + + DESFireEV2 = 0x6000, + DESFireEV2_2K = 0x6100, + DESFireEV2_4K = 0x6200, + DESFireEV2_8K = 0x6300, + DESFireEV2_16K = 0x6400, + DESFireEV2_32K = 0x6500, + // 0x5C - 0x5F = RFU + + SmartMX_DESFireEV2_2K = 0x6900, + SmartMX_DESFireEV2_4K = 0x6A00, + SmartMX_DESFireEV2_8K = 0x6B00, + SmartMX_DESFireEV2_16K = 0x6C00, + SmartMX_DESFireEV2_32K = 0x6D00, + // 0x5C - 0x5F = RFU + + DESFireEV3 = 0x7000, + DESFireEV3_2K = 0x7100, + DESFireEV3_4K = 0x7200, + DESFireEV3_8K = 0x7300, + DESFireEV3_16K = 0x7400, + DESFireEV3_32K = 0x7500, + // 0x5C - 0x5F = RFU + + SmartMX_DESFireEV3_2K = 0x7900, + SmartMX_DESFireEV3_4K = 0x7A00, + SmartMX_DESFireEV3_8K = 0x7B00, + SmartMX_DESFireEV3_16K = 0x7C00, + SmartMX_DESFireEV3_32K = 0x7D00, + // 0x5C - 0x5F = RFU + + DESFireLight = 0x8000, + + MifareUltralight = 0x9000, + MifareUltralightC = 0x9100, + MifareUltralightC_EV1 = 0x9200, + + NTAG_210 = 0xA000, + NTAG_211 = 0xA100, + NTAG_212 = 0xA200, + NTAG_213 = 0xA300, + NTAG_214 = 0xA400, + NTAG_215 = 0xA500, + NTAG_216 = 0xA600, + // 0xA7 - 0xA9 = RFU + NTAG_424 = 0xAA00, + NTAG_426 = 0xAB00, + + MifareMini = 0xB000 }; /// diff --git a/RFiDGear/DataAccessLayer/Local/CustomConverter.cs b/RFiDGear/DataAccessLayer/Local/CustomConverter.cs index 1284739..48dc484 100644 --- a/RFiDGear/DataAccessLayer/Local/CustomConverter.cs +++ b/RFiDGear/DataAccessLayer/Local/CustomConverter.cs @@ -1,7 +1,5 @@ using RFiDGear.DataAccessLayer; -using Elatec.NET; - using System; using System.Globalization; using System.Collections.Generic; diff --git a/RFiDGear/DataAccessLayer/Local/ResourceLoader.cs b/RFiDGear/DataAccessLayer/Local/ResourceLoader.cs index 3d0f5ba..c653f17 100644 --- a/RFiDGear/DataAccessLayer/Local/ResourceLoader.cs +++ b/RFiDGear/DataAccessLayer/Local/ResourceLoader.cs @@ -1,7 +1,7 @@ using RFiDGear.DataAccessLayer; using RFiDGear.Model; -using Log4CSharp; +using Microsoft.Extensions.Logging; using System; using System.Collections.ObjectModel; @@ -10,6 +10,8 @@ using System.Windows; using System.Windows.Data; using System.Windows.Markup; +using System.Diagnostics; +using System.Reflection; namespace RFiDGear.DataAccessLayer { @@ -70,7 +72,7 @@ public EnumerateExtension(Type type) var settings = new SettingsReaderWriter(); resManager = new ResourceManager("RFiDGear.Resources.Manifest", System.Reflection.Assembly.GetExecutingAssembly()); - settings.ReadSettings(); + settings.ReadSettings().GetAwaiter().GetResult(); cultureInfo = (new DefaultSpecification().DefaultLanguage == "german") ? new CultureInfo("de") : new CultureInfo("en"); } @@ -97,7 +99,7 @@ public override object ProvideValue(IServiceProvider serviceProvider) /// public sealed class ResourceLoader : IValueConverter, IDisposable { - private static readonly string FacilityName = "RFiDGear"; + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private readonly ResourceManager resManager; /// @@ -150,7 +152,7 @@ public object Convert(object value, Type targetType, object parameter, CultureIn } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); throw new ArgumentOutOfRangeException( string.Format("parameter:{0}\nvalue:{1}", @@ -206,7 +208,7 @@ public static string GetResource(string resName) { using (var settings = new SettingsReaderWriter()) { - settings.ReadSettings(); + settings.ReadSettings().GetAwaiter().GetResult(); var ressource = new ResourceManager("RFiDGear.Resources.Manifest", System.Reflection.Assembly.GetExecutingAssembly()) .GetString(resName, (settings.DefaultSpecification.DefaultLanguage == "german") ? new CultureInfo("de") : new CultureInfo("en")); @@ -217,7 +219,8 @@ public static string GetResource(string resName) } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + EventLog eventLog2 = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); + eventLog2.WriteEntry(e.Message, EventLogEntryType.Error); return string.Empty; } } diff --git a/RFiDGear/DataAccessLayer/Remote/FromFile/DatabaseReaderWriter.cs b/RFiDGear/DataAccessLayer/Remote/FromFile/DatabaseReaderWriter.cs index 699eeb3..cd48310 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromFile/DatabaseReaderWriter.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromFile/DatabaseReaderWriter.cs @@ -3,6 +3,7 @@ using System; using System.Collections.ObjectModel; using System.ComponentModel; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; @@ -11,7 +12,7 @@ using System.Xml; using System.Xml.Serialization; using Ionic.Zip; -using Log4CSharp; + using RFiDGear.Model; using RFiDGear.ViewModel; @@ -23,9 +24,8 @@ namespace RFiDGear.DataAccessLayer public class DatabaseReaderWriter { #region fields - private static readonly string FacilityName = "RFiDGear"; - private readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version; + private readonly EventLog eventLog = new EventLog("Application", ".", "RFiDGear"); private const string chipDatabaseFileName = "chipdatabase.xml"; private const string taskDatabaseFileNameCompressed = "chipdatabase.rfPrj"; @@ -81,7 +81,7 @@ public DatabaseReaderWriter() } catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}; {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); return; } } @@ -90,7 +90,7 @@ public DatabaseReaderWriter() /// /// /// - public bool ReadDatabase(string _fileName = "") + public async Task ReadDatabase(string _fileName = "") { var verInfo = 0; FileInfo file; @@ -104,86 +104,89 @@ public bool ReadDatabase(string _fileName = "") file = new FileInfo(_fileName); } - try + await Task.Run(() => { - var doc = new XmlDocument(); - - if (file.Extension.ToLower(CultureInfo.CurrentCulture) == ".xml") + try { - doc.Load(@_fileName); - TextReader reader = new StreamReader(_fileName); - - var node = doc.SelectSingleNode("//ManifestVersion"); - verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); + var doc = new XmlDocument(); - try - { - AsyncRelayCommandLoadDB.ExecuteAsync(reader); - } - catch (Exception e) + if (file.Extension.ToLower(CultureInfo.CurrentCulture) == ".xml") { - LogWriter.CreateLogEntry(e, FacilityName); - } + doc.Load(@_fileName); + TextReader reader = new StreamReader(_fileName); - } + var node = doc.SelectSingleNode("//ManifestVersion"); + verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); - if (file.Extension.ToLower(CultureInfo.CurrentCulture) == ".rfprj") - { - using (var zip1 = ZipFile.Read(string.IsNullOrWhiteSpace(_fileName) ? - @Path.Combine(appDataPath, taskDatabaseFileNameCompressed) : - _fileName)) + try + { + AsyncRelayCommandLoadDB.Execute(reader); + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + } + + } + + if (file.Extension.ToLower(CultureInfo.CurrentCulture) == ".rfprj") { - if (Directory.GetFiles(appDataPath, "*.tmp").Length > 0) + using (var zip1 = ZipFile.Read(string.IsNullOrWhiteSpace(_fileName) ? + @Path.Combine(appDataPath, taskDatabaseFileNameCompressed) : + _fileName)) { - foreach (var tempFile in Directory.GetFiles(appDataPath, "*.tmp")) + if (Directory.GetFiles(appDataPath, "*.tmp").Length > 0) { - File.Delete(tempFile); + foreach (var tempFile in Directory.GetFiles(appDataPath, "*.tmp")) + { + File.Delete(tempFile); + } } + zip1.ExtractAll(appDataPath, ExtractExistingFileAction.OverwriteSilently); } - zip1.ExtractAll(appDataPath, ExtractExistingFileAction.OverwriteSilently); - } - TextReader reader = null; + TextReader reader = null; - if (File.Exists(@Path.Combine(appDataPath, file.Name))) - { - doc.Load(@Path.Combine(appDataPath, file.Name)); - var node = doc.SelectSingleNode("//ManifestVersion"); - verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); - reader = new StreamReader(@Path.Combine(appDataPath, file.Name)); - } // old Variant. Needed to open old databases - else if(File.Exists(@Path.Combine(appDataPath, taskDatabaseFileName))) - { - doc.Load(@Path.Combine(appDataPath, taskDatabaseFileName)); - var node = doc.SelectSingleNode("//ManifestVersion"); - verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); - reader = new StreamReader(@Path.Combine(appDataPath, taskDatabaseFileName)); - } + if (File.Exists(@Path.Combine(appDataPath, file.Name))) + { + doc.Load(@Path.Combine(appDataPath, file.Name)); + var node = doc.SelectSingleNode("//ManifestVersion"); + verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); + reader = new StreamReader(@Path.Combine(appDataPath, file.Name)); + } // old Variant. Needed to open old databases + else if(File.Exists(@Path.Combine(appDataPath, taskDatabaseFileName))) + { + doc.Load(@Path.Combine(appDataPath, taskDatabaseFileName)); + var node = doc.SelectSingleNode("//ManifestVersion"); + verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); + reader = new StreamReader(@Path.Combine(appDataPath, taskDatabaseFileName)); + } - try - { - XmlSerializer serializer = new XmlSerializer(typeof(ChipTaskHandlerModel)); - SetupModel = (serializer.Deserialize(reader) as ChipTaskHandlerModel); - reader.Close(); + try + { + XmlSerializer serializer = new XmlSerializer(typeof(ChipTaskHandlerModel)); + SetupModel = (serializer.Deserialize(reader) as ChipTaskHandlerModel); + reader.Close(); + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + } } - catch (Exception e) + + if (verInfo > Convert.ToInt32(string.Format("{0}{1}{2}", Version.Major, Version.Minor, Version.Build))) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(string.Format("{0}; {1}", DateTime.Now, string.Format("database that was tried to open is newer ({0}) than this version of rfidgear ({1})" + , verInfo, Convert.ToInt32(string.Format("{0}{1}{2}", Version.Major, Version.Minor, Version.Build)))), EventLogEntryType.Warning); + return ; } } - - if (verInfo > Convert.ToInt32(string.Format("{0}{1}{2}", Version.Major, Version.Minor, Version.Build))) + catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}; {1}", DateTime.Now, string.Format("database that was tried to open is newer ({0}) than this version of rfidgear ({1})" - , verInfo, Convert.ToInt32(string.Format("{0}{1}{2}", Version.Major, Version.Minor, Version.Build)))), FacilityName); - return true; + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + return ; } - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - return true; - } + }).ConfigureAwait(false); return false; } @@ -210,7 +213,7 @@ public void WriteDatabase(ObservableCollection obj } catch (XmlException e) { - LogWriter.CreateLogEntry(string.Format("{0}; {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); Environment.Exit(0); } } @@ -248,7 +251,7 @@ public void WriteDatabase(ChipTaskHandlerModel objModel, string _path = "") } catch (XmlException e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } @@ -256,31 +259,5 @@ public void DeleteDatabase() { File.Delete(Path.Combine(appDataPath, chipDatabaseFileName)); } - - private object LoadXML(TextReader reader) - { - try - { - var serializer = new XmlSerializer(typeof(ChipTaskHandlerModel)); - return (serializer.Deserialize(reader) as ChipTaskHandlerModel); - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - - try - { - var serializer = new XmlSerializer(typeof(ObservableCollection)); - return serializer.Deserialize(reader) as ObservableCollection; - } - - catch (Exception innerE) - { - LogWriter.CreateLogEntry(innerE, FacilityName); - } - } - - return null; - } } } \ No newline at end of file diff --git a/RFiDGear/DataAccessLayer/Remote/FromFile/ReportReaderWriter.cs b/RFiDGear/DataAccessLayer/Remote/FromFile/ReportReaderWriter.cs index 4d235a5..8260ba3 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromFile/ReportReaderWriter.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromFile/ReportReaderWriter.cs @@ -1,13 +1,12 @@ -using GemBox.Pdf; - -using Log4CSharp; - -using System; +using System; using System.Collections.ObjectModel; -using System.Collections.Generic; +using System.Diagnostics; using System.IO; +using System.Linq; using System.Reflection; +using System.Threading.Tasks; using System.Xml; +using GemBox.Pdf; namespace RFiDGear.DataAccessLayer { @@ -17,10 +16,8 @@ namespace RFiDGear.DataAccessLayer public class ReportReaderWriter : IDisposable { #region fields - private static readonly string FacilityName = "RFiDGear"; - private readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version; - + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private const string reportTemplateTempFileName = "temptemplate.pdf"; private readonly string appDataPath; public string ReportOutputPath { get; set; } @@ -51,7 +48,7 @@ public ReportReaderWriter() } catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}; {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); return; } } @@ -78,7 +75,7 @@ public ObservableCollection GetReportFields() } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } @@ -87,82 +84,96 @@ public ObservableCollection GetReportFields() } catch (XmlException e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); return null; } } - public void SetReportField(string _field, string _value) + public async Task SetReportField(string _field, string _value) { if (!String.IsNullOrWhiteSpace(ReportOutputPath)) { try { - using (var pdfDoc = PdfDocument.Load(ReportTemplateFile)) // (new PdfReader(ReportTemplateFile), new PdfWriter(ReportOutputPath))) + await Task.Run(() => { - try + using (var pdfDoc = PdfDocument.Load(ReportTemplateFile)) { - ReportTemplateFile = System.IO.Path.Combine(appDataPath, reportTemplateTempFileName); + try + { + ReportTemplateFile = System.IO.Path.Combine(appDataPath, reportTemplateTempFileName); - var form = pdfDoc.Form; - pdfDoc.Info.Title = "RFiDGear Report"; - pdfDoc.Info.Author = "RFiDGear"; + var form = pdfDoc.Form; + pdfDoc.Info.Title = "RFiDGear Report"; + pdfDoc.Info.Author = "RFiDGear"; - pdfDoc.Form.Fields[_field].Hidden = false; - pdfDoc.Form.Fields[_field].ReadOnly = false; - pdfDoc.Form.Fields[_field].Value = _value; + if (pdfDoc.Form.Fields.Any(x => x.Name == _field)) + { + pdfDoc.Form.Fields[_field].Hidden = false; + pdfDoc.Form.Fields[_field].ReadOnly = false; + pdfDoc.Form.Fields[_field].Value = _value; + } - pdfDoc.Save(ReportOutputPath); - pdfDoc.Close(); + pdfDoc.Save(ReportOutputPath); + pdfDoc.Close(); - File.Copy(ReportOutputPath, System.IO.Path.Combine(appDataPath, reportTemplateTempFileName), true); - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); + File.Copy(ReportOutputPath, System.IO.Path.Combine(appDataPath, reportTemplateTempFileName), true); + } + catch (Exception e) + { + eventLog.WriteEntry(string.Format(e.Message + "; SetReportField: " + _field), EventLogEntryType.Error); + } } - } + }).ConfigureAwait(true); + + return; } catch (XmlException e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } - + return; } - public void ConcatReportField(string _field, string _value) + public async Task ConcatReportField(string _field, string _value) { if (!String.IsNullOrWhiteSpace(ReportOutputPath)) { try { - ReportTemplateFile = System.IO.Path.Combine(appDataPath, reportTemplateTempFileName); - - using (var pdfDoc = PdfDocument.Load(ReportTemplateFile)) + await Task.Run(() => { - try + ReportTemplateFile = System.IO.Path.Combine(appDataPath, reportTemplateTempFileName); + + using (var pdfDoc = PdfDocument.Load(ReportTemplateFile)) { - var form = pdfDoc.Form; + try + { + var form = pdfDoc.Form; - pdfDoc.Form.Fields[_field].Hidden = false; - pdfDoc.Form.Fields[_field].ReadOnly = false; - pdfDoc.Form.Fields[_field].Value = string.Format("{0}{1}", pdfDoc.Form.Fields[_field]?.Value, _value); + pdfDoc.Form.Fields[_field].Hidden = false; + pdfDoc.Form.Fields[_field].ReadOnly = false; + pdfDoc.Form.Fields[_field].Value = string.Format("{0}{1}", pdfDoc.Form.Fields[_field]?.Value, _value); - pdfDoc.Save(ReportOutputPath); - pdfDoc.Close(); + pdfDoc.Save(ReportOutputPath); + pdfDoc.Close(); - File.Copy(ReportOutputPath, System.IO.Path.Combine(appDataPath, reportTemplateTempFileName), true); - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); + File.Copy(ReportOutputPath, System.IO.Path.Combine(appDataPath, reportTemplateTempFileName), true); + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + } } - } + + return; + }).ConfigureAwait(false); + } catch (XmlException e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } @@ -187,7 +198,7 @@ protected virtual void Dispose(bool disposing) catch (XmlException e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } diff --git a/RFiDGear/DataAccessLayer/Remote/FromFile/SettingsReaderWriter.cs b/RFiDGear/DataAccessLayer/Remote/FromFile/SettingsReaderWriter.cs index 397a387..3e14dc0 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromFile/SettingsReaderWriter.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromFile/SettingsReaderWriter.cs @@ -1,15 +1,13 @@ -using RFiDGear.DataAccessLayer; -using RFiDGear.Model; - -using Log4CSharp; - -using System; +using System; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; +using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; +using RFiDGear.Model; namespace RFiDGear { @@ -19,8 +17,7 @@ namespace RFiDGear public class SettingsReaderWriter : IDisposable { #region fields - private static readonly string FacilityName = "RFiDGear"; - + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private readonly string _settingsFileFileName = "settings.xml"; private readonly string _updateConfigFileFileName = "update.xml"; private readonly string _updateURL = @"https://github.com/c3rebro/RFiDGear/releases/latest/download/update.xml"; @@ -30,7 +27,7 @@ public class SettingsReaderWriter : IDisposable private readonly string _infoText = "Version Info\n\ngoes here! \n==>"; private readonly string _baseUri = @"https://github.com/c3rebro/RFiDGear/releases/latest/download/"; - private readonly XmlWriter xmlWriter; + private readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version; private readonly string appDataPath; @@ -41,7 +38,7 @@ public DefaultSpecification DefaultSpecification { get { - ReadSettings(); + ReadSettings().GetAwaiter().GetResult(); return defaultSpecification ?? new DefaultSpecification(); } @@ -50,7 +47,7 @@ public DefaultSpecification DefaultSpecification defaultSpecification = value; if (defaultSpecification != null) { - SaveSettings(); + SaveSettings().GetAwaiter().GetResult(); } } } @@ -71,50 +68,10 @@ public SettingsReaderWriter() { Directory.CreateDirectory(appDataPath); } - - var xmlSettings = new XmlWriterSettings(); - xmlSettings.Encoding = new UTF8Encoding(false); - - xmlWriter = XmlWriter.Create(Path.Combine(appDataPath, _updateConfigFileFileName), xmlSettings); - xmlWriter.WriteStartDocument(); - xmlWriter.WriteStartElement("Manifest"); - xmlWriter.WriteAttributeString("version", string.Format("{0}.{1}.{2}", Version.Major, Version.Minor, Version.Build)); - - xmlWriter.WriteEndElement(); - xmlWriter.Close(); - - var doc = new XmlDocument(); - doc.Load(Path.Combine(appDataPath, _updateConfigFileFileName)); - - if (doc.SelectSingleNode("//CheckInterval") == null) - { - var CheckIntervalElem = doc.CreateElement("CheckInterval"); - var RemoteConfigUriElem = doc.CreateElement("RemoteConfigUri"); - var SecurityTokenElem = doc.CreateElement("SecurityToken"); - var BaseUriElem = doc.CreateElement("BaseUri"); - var PayLoadElem = doc.CreateElement("Payload"); - var InfoTextElem = doc.CreateElement("VersionInfoText"); - - doc.DocumentElement.AppendChild(CheckIntervalElem); - doc.DocumentElement.AppendChild(RemoteConfigUriElem); - doc.DocumentElement.AppendChild(SecurityTokenElem); - doc.DocumentElement.AppendChild(BaseUriElem); - doc.DocumentElement.AppendChild(PayLoadElem); - doc.DocumentElement.AppendChild(InfoTextElem); - - CheckIntervalElem.InnerText = _updateInterval.ToString(CultureInfo.CurrentCulture); - RemoteConfigUriElem.InnerText = _updateURL; - SecurityTokenElem.InnerText = _securityToken; - BaseUriElem.InnerText = _baseUri; - PayLoadElem.InnerText = _payload; - InfoTextElem.InnerText = _infoText; - - doc.Save(Path.Combine(appDataPath, _updateConfigFileFileName)); - } } catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } if (!File.Exists(Path.Combine(appDataPath, _settingsFileFileName))) @@ -133,7 +90,7 @@ public SettingsReaderWriter() } catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}; {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } } @@ -142,16 +99,65 @@ public SettingsReaderWriter() /// /// /// - public bool ReadSettings() + public void InitUpdateFile() + { + XmlWriter xmlWriter; + var xmlSettings = new XmlWriterSettings(); + xmlSettings.Encoding = new UTF8Encoding(false); + + xmlWriter = XmlWriter.Create(Path.Combine(appDataPath, _updateConfigFileFileName), xmlSettings); + xmlWriter.WriteStartDocument(); + xmlWriter.WriteStartElement("Manifest"); + xmlWriter.WriteAttributeString("version", string.Format("{0}.{1}.{2}", Version.Major, Version.Minor, Version.Build)); + + xmlWriter.WriteEndElement(); + xmlWriter.Close(); + + var doc = new XmlDocument(); + doc.Load(Path.Combine(appDataPath, _updateConfigFileFileName)); + + if (doc.SelectSingleNode("//CheckInterval") == null) + { + var CheckIntervalElem = doc.CreateElement("CheckInterval"); + var RemoteConfigUriElem = doc.CreateElement("RemoteConfigUri"); + var SecurityTokenElem = doc.CreateElement("SecurityToken"); + var BaseUriElem = doc.CreateElement("BaseUri"); + var PayLoadElem = doc.CreateElement("Payload"); + var InfoTextElem = doc.CreateElement("VersionInfoText"); + + doc.DocumentElement.AppendChild(CheckIntervalElem); + doc.DocumentElement.AppendChild(RemoteConfigUriElem); + doc.DocumentElement.AppendChild(SecurityTokenElem); + doc.DocumentElement.AppendChild(BaseUriElem); + doc.DocumentElement.AppendChild(PayLoadElem); + doc.DocumentElement.AppendChild(InfoTextElem); + + CheckIntervalElem.InnerText = _updateInterval.ToString(CultureInfo.CurrentCulture); + RemoteConfigUriElem.InnerText = _updateURL; + SecurityTokenElem.InnerText = _securityToken; + BaseUriElem.InnerText = _baseUri; + PayLoadElem.InnerText = _payload; + InfoTextElem.InnerText = _infoText; + + doc.Save(Path.Combine(appDataPath, _updateConfigFileFileName)); + } + } + + /// + /// + /// + /// + public async Task ReadSettings() { - return ReadSettings(""); + await ReadSettings("").ConfigureAwait(false); + return; } /// /// /// /// - public bool ReadSettings(string _fileName) + public async Task ReadSettings(string _fileName) { TextReader reader; int verInfo; @@ -167,43 +173,38 @@ public bool ReadSettings(string _fileName) try { - var serializer = new XmlSerializer(typeof(DefaultSpecification)); - - if (string.IsNullOrWhiteSpace(_fileName) && File.Exists(Path.Combine(appDataPath, _settingsFileFileName))) + await Task.Run(() => { - doc.Load(@Path.Combine(appDataPath, _settingsFileFileName)); + var serializer = new XmlSerializer(typeof(DefaultSpecification)); - var node = doc.SelectSingleNode("//ManifestVersion"); - verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); + if (string.IsNullOrWhiteSpace(_fileName) && File.Exists(Path.Combine(appDataPath, _settingsFileFileName))) + { + doc.Load(@Path.Combine(appDataPath, _settingsFileFileName)); - reader = new StreamReader(Path.Combine(appDataPath, _settingsFileFileName)); - } - else - { - doc.Load(_fileName); + var node = doc.SelectSingleNode("//ManifestVersion"); + verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); - var node = doc.SelectSingleNode("//ManifestVersion"); - verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); + reader = new StreamReader(Path.Combine(appDataPath, _settingsFileFileName)); + } + else + { + doc.Load(_fileName); - reader = new StreamReader(_fileName); - } + var node = doc.SelectSingleNode("//ManifestVersion"); + verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty)); - if (verInfo > Convert.ToInt32(string.Format("{0}{1}{2}", Version.Major, Version.Minor, Version.Build))) - { - throw new Exception( - string.Format("database that was tried to open is newer ({0}) than this version of rfidgear ({1})" - , verInfo, Convert.ToInt32(string.Format("{0}{1}{2}", Version.Major, Version.Minor, Version.Build)) - ) - ); - } + reader = new StreamReader(_fileName); + } + + defaultSpecification = (serializer.Deserialize(reader) as DefaultSpecification); - defaultSpecification = (serializer.Deserialize(reader) as DefaultSpecification); + reader.Close(); - reader.Close(); + }).ConfigureAwait(false); } catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); return true; } @@ -217,24 +218,32 @@ public bool ReadSettings(string _fileName) /// /// /// - public bool SaveSettings(string _path = "") + public async Task SaveSettings(string _path = "") { try { - TextWriter textWriter; - var serializer = new XmlSerializer(typeof(DefaultSpecification)); + await Task.Run(() => { + + if (defaultSpecification == null) + { + return; + } - textWriter = new StreamWriter(!string.IsNullOrEmpty(_path) ? @_path : @Path.Combine(appDataPath, _settingsFileFileName), false); + TextWriter textWriter; + var serializer = new XmlSerializer(typeof(DefaultSpecification)); + + textWriter = new StreamWriter(!string.IsNullOrEmpty(_path) ? @_path : @Path.Combine(appDataPath, _settingsFileFileName), false); - serializer.Serialize(textWriter, defaultSpecification); + serializer.Serialize(textWriter, defaultSpecification); - textWriter.Close(); + textWriter.Close(); + }).ConfigureAwait(false); return true; } catch (XmlException e) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); return false; } } @@ -247,25 +256,15 @@ protected virtual void Dispose(bool disposing) { try { - if (xmlWriter != null) - { - xmlWriter.Close(); - } - defaultSpecification = null; - // Dispose any managed objects - // ... } catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } - // Now disposed of any unmanaged objects - // ... - _disposed = true; } } diff --git a/RFiDGear/DataAccessLayer/Remote/FromIO/ElatecNetProvider.cs b/RFiDGear/DataAccessLayer/Remote/FromIO/ElatecNetProvider.cs index 287c630..5ed41b3 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromIO/ElatecNetProvider.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromIO/ElatecNetProvider.cs @@ -1,28 +1,22 @@ -using Elatec.NET.Model; -using Elatec.NET; - -using RFiDGear.Model; - -using Log4CSharp; - +//using Elatec.NET.Model; using System; -using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; -using System.Text; +using System.Reflection; +using System.Threading; using System.Threading.Tasks; -using System.Security.Cryptography; using ByteArrayHelper.Extensions; -using RFiDGear.ViewModel; -using System.Runtime.InteropServices.WindowsRuntime; +using Elatec.NET; +using Elatec.NET.Cards.Mifare; +using RFiDGear.Model; namespace RFiDGear.DataAccessLayer.Remote.FromIO { public class ElatecNetProvider : ReaderDevice, IDisposable { - private static readonly string FacilityName = "RFiDGear"; - - private readonly TWN4ReaderDevice readerDevice; + private TWN4ReaderDevice readerDevice; + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private GenericChipModel hfTag; private GenericChipModel lfTag; @@ -30,259 +24,377 @@ public class ElatecNetProvider : ReaderDevice, IDisposable private bool _disposed; + public override string ReaderUnitName + { + get; set; + } + public override string ReaderUnitVersion + { + get; set; + } + #region Constructor - public ElatecNetProvider() + private async Task Initialize() { + if (GenericChip == null) + { + GenericChip = new List(); + } + try { - readerDevice = new TWN4ReaderDevice(PortNumber); + var readerList = TWN4ReaderDevice.Instance; + + if (readerList != null && readerList.Count > 0) + { + readerDevice = readerList.FirstOrDefault(); + + if (readerDevice.IsConnected) + { + ReaderUnitVersion = await readerDevice.GetVersionStringAsync(); + } + else if (readerDevice != null && readerDevice.AvailableReadersCount >= 1 && !readerDevice.IsConnected) + { + if (await readerDevice.ConnectAsync()) + { + ReaderUnitVersion = await readerDevice.GetVersionStringAsync(); + } + } + } } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } - public ElatecNetProvider(int _comPort) + public ElatecNetProvider() { - try + if (GenericChip == null) { - readerDevice = new TWN4ReaderDevice(_comPort); + GenericChip = new List(); } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } - } #endregion #region Common + /// + /// + /// + public override bool IsConnected => readerDevice?.IsConnected == true; + /// /// /// /// - public override ERROR ReadChipPublic() + public async override Task ReadChipPublic() { try { - if (readerDevice != null) + if (readerDevice == null) + { + await Initialize(); + } + + else if (readerDevice != null) { + if (!readerDevice.IsConnected) { - Instance.Connect(); + await readerDevice.ConnectAsync(); } - var tmpTag = readerDevice.GetSingleChip(true); - hfTag = new GenericChipModel(tmpTag.UID, (RFiDGear.DataAccessLayer.CARD_TYPE)tmpTag.CardType, tmpTag.SAK, tmpTag.RATS, tmpTag.VersionL4); - tmpTag = readerDevice.GetSingleChip(false); - lfTag = new GenericChipModel(tmpTag.UID, (RFiDGear.DataAccessLayer.CARD_TYPE)tmpTag.CardType); - tmpTag = readerDevice.GetSingleChip(true, true); - legicTag = new GenericChipModel(tmpTag.UID, (RFiDGear.DataAccessLayer.CARD_TYPE)tmpTag.CardType); - readerDevice.GetSingleChip(true); + await readerDevice.SetTagTypesAsync(LFTagTypes.NOTAG, HFTagTypes.AllHFTags & ~HFTagTypes.LEGIC); + var tmpTag = await readerDevice.GetSingleChipAsync(); - if ( - !( - string.IsNullOrWhiteSpace(hfTag?.UID) & - string.IsNullOrWhiteSpace(lfTag?.UID) & - string.IsNullOrWhiteSpace(legicTag?.UID) - ) - ) + if (tmpTag != null && tmpTag.ChipType == ChipType.MIFARE) { - try + if ((MifareChipSubType)((byte)(tmpTag as MifareChip).SubType & 0xF0) == MifareChipSubType.MifareClassic) + { + hfTag = new MifareClassicChipModel(tmpTag.UIDHexString, (CARD_TYPE)((short)(tmpTag as MifareChip).SubType << 8)); + } + else if ((MifareChipSubType)((byte)(tmpTag as MifareChip).SubType & 0x40) == MifareChipSubType.DESFire) + { + hfTag = new MifareDesfireChipModel(tmpTag.UIDHexString, (CARD_TYPE)((short)(tmpTag as MifareChip).SubType << 8), + ByteArrayConverter.GetStringFrom((tmpTag as MifareChip).SAK), + ByteArrayConverter.GetStringFrom((tmpTag as MifareChip).ATS), + ByteArrayConverter.GetStringFrom((tmpTag as MifareChip).VersionL4)); + } + else { - readerDevice.GreenLED(true); - readerDevice.RedLED(false); + hfTag = new GenericChipModel(tmpTag.UIDHexString, (CARD_TYPE)((short)(tmpTag as MifareChip).SubType << 8)); + } + } + else if (tmpTag == null) + { + hfTag = null; + } - GenericChip = new GenericChipModel(hfTag.UID, - (CARD_TYPE)hfTag.CardType, - hfTag.SAK, - hfTag.RATS, - hfTag.VersionL4 - ); + await readerDevice.SetTagTypesAsync(LFTagTypes.AllLFTags, HFTagTypes.NOTAG); + tmpTag = await readerDevice.GetSingleChipAsync(); + lfTag = tmpTag != null ? new GenericChipModel(tmpTag.UIDHexString, (CARD_TYPE)tmpTag.ChipType) : null; - if (lfTag != null && lfTag?.CardType != CARD_TYPE.NOTAG) - { - if(GenericChip != null && GenericChip.CardType != CARD_TYPE.NOTAG) - { - GenericChip.Child = new GenericChipModel(lfTag.UID, lfTag.CardType); - } - else - { - GenericChip = new GenericChipModel(lfTag.UID, lfTag.CardType); - } - } - else if (legicTag != null && legicTag?.CardType != CARD_TYPE.NOTAG) - { - if (GenericChip != null && GenericChip.CardType != CARD_TYPE.NOTAG) - { - GenericChip.Child = new GenericChipModel(legicTag.UID, legicTag.CardType); - } - else - { - GenericChip = new GenericChipModel(legicTag.UID, legicTag.CardType); - } - } - //readerDevice.GetSingleChip(true); + await readerDevice.SetTagTypesAsync(LFTagTypes.NOTAG, HFTagTypes.LEGIC); + tmpTag = await readerDevice.GetSingleChipAsync(); + legicTag = tmpTag != null ? new GenericChipModel(tmpTag.UIDHexString, (CARD_TYPE)tmpTag.ChipType) : null; - return ERROR.NoError; - } - catch (Exception e) + await readerDevice.SetTagTypesAsync(LFTagTypes.NOTAG, HFTagTypes.AllHFTags); + + if (!string.IsNullOrWhiteSpace(hfTag?.UID) && GenericChip.Any(x => x.UID == hfTag.UID)) + { + return ERROR.NoError; + } + + if (!string.IsNullOrWhiteSpace(hfTag?.UID) && !GenericChip.Any(x => x.UID == hfTag.UID)) + { + GenericChip = new List(); + + if (!string.IsNullOrWhiteSpace(hfTag?.UID)) { - LogWriter.CreateLogEntry(e, FacilityName); - return ERROR.IOError; + GenericChip.Add(hfTag); + + if (GenericChip[0].Childs == null) + { + GenericChip[0].Childs = new List(); + } } } - else + + if (!string.IsNullOrEmpty(lfTag?.UID)) { - readerDevice.Beep(3, 25, 600, 100); - readerDevice.RedLED(true); - GenericChip = null; + GenericChip[0].Childs.Add(lfTag); + } - return ERROR.NotReadyError; + if (!string.IsNullOrEmpty(legicTag?.UID)) + { + GenericChip[0].Childs.Add(legicTag); } } - else + if (hfTag == null && lfTag == null && legicTag == null) { - return ERROR.IOError; + GenericChip = new List(); } + + return ERROR.NoError; } catch (Exception e) { - if (readerDevice != null) - { - readerDevice.Dispose(); - } - - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); return ERROR.IOError; } } + /// /// /// /// - public override ERROR Connect() + public async override Task ConnectAsync() { - readerDevice.Beep(1, 50, 1000, 100); - readerDevice.GreenLED(true); - readerDevice.RedLED(false); - return TWN4ReaderDevice.Instance.Connect() == true ? ERROR.NoError : ERROR.IOError; + readerDevice = TWN4ReaderDevice.Instance.FirstOrDefault(); + + if (readerDevice == null) + { + return ERROR.NotReadyError; + } + + if (readerDevice != null && !readerDevice.IsConnected) + { + var result = false; + + if (!readerDevice.IsConnected) + { + result = await readerDevice.ConnectAsync(); + } + + if (result) + { + ReaderUnitVersion = await readerDevice.GetVersionStringAsync(); + return ERROR.NoError; + } + } + + return ERROR.NotReadyError; } #endregion #region MifareClassic - public override ERROR WriteMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey, byte[] buffer) + + public async override Task WriteMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey, byte[] buffer) { - if (!readerDevice.MifareClassicLogin(_aKey, 0, (byte)CustomConverter.GetSectorNumberFromChipBasedDataBlockNumber(_blockNumber))) // No Access Allowed, try bKey + return await Task.Run(async () => { - readerDevice.MifareClassicLogin(_bKey, 1, (byte)CustomConverter.GetSectorNumberFromChipBasedDataBlockNumber(_blockNumber)); - - } // Login + try + { + await readerDevice.MifareClassic_LoginAsync(_aKey, 0, (byte)CustomConverter.GetSectorNumberFromChipBasedDataBlockNumber(_blockNumber)); + } + catch + { + try + { + await readerDevice.MifareClassic_LoginAsync(_bKey, 1, (byte)CustomConverter.GetSectorNumberFromChipBasedDataBlockNumber(_blockNumber)); + } + catch + { + try + { + await readerDevice.MifareClassic_WriteBlockAsync(buffer, (byte)_blockNumber); + } + catch + { + return ERROR.AuthenticationError; + } + } + } // Login + return ERROR.NoError; + }); - return readerDevice.MifareClassicWriteBlock(buffer, (byte)_blockNumber) == true ? ERROR.NoError : ERROR.AuthenticationError; } - public override ERROR ReadMifareClassicSingleSector(int sectorNumber, string aKey, string bKey) + public async override Task ReadMifareClassicSingleSector(int sectorNumber, string aKey, string bKey) { - return readWriteAccessOnClassicSector(sectorNumber, aKey, bKey, null); + return await ReadWriteAccessOnClassicSector(sectorNumber, aKey, bKey, null); } - public override ERROR WriteMifareClassicSingleSector(int sectorNumber, string aKey, string bKey, byte[] buffer) + public async override Task WriteMifareClassicSingleSector(int sectorNumber, string aKey, string bKey, byte[] buffer) { - return readWriteAccessOnClassicSector(sectorNumber, aKey, bKey, buffer); + return await ReadWriteAccessOnClassicSector(sectorNumber, aKey, bKey, buffer); } - - public override ERROR WriteMifareClassicWithMAD(int _madApplicationID, int _madStartSector, + + public async override Task WriteMifareClassicWithMAD(int _madApplicationID, int _madStartSector, string _aKeyToUse, string _bKeyToUse, string _aKeyToWrite, string _bKeyToWrite, - string _madAKeyToUse, string _madBKeyToUse, string _madAKeyToWrite, - string _madBKeyToWrite, byte[] buffer, byte _madGPB, SectorAccessBits _sab, + string _madAKeyToUse, string _madBKeyToUse, string _madAKeyToWrite, + string _madBKeyToWrite, byte[] buffer, byte _madGPB, SectorAccessBits _sab, bool _useMADToAuth, bool _keyToWriteUseMAD) { throw new NotImplementedException(); } - public override ERROR ReadMifareClassicWithMAD(int madApplicationID, string _aKeyToUse, - string _bKeyToUse, string _madAKeyToUse, string _madBKeyToUse, int _length, byte _madGPB, + public async override Task ReadMifareClassicWithMAD(int madApplicationID, string _aKeyToUse, + string _bKeyToUse, string _madAKeyToUse, string _madBKeyToUse, int _length, byte _madGPB, bool _useMADToAuth, bool _aiToUseIsMAD) { throw new NotImplementedException(); } - - private ERROR readWriteAccessOnClassicSector(int sectorNumber, string aKey, string bKey, byte[] buffer) - { - Sector = new MifareClassicSectorModel(); - var elatecSpecificSectorNumber = sectorNumber > 31 ? (sectorNumber - 32) * 4 + 32 : sectorNumber; // elatec uses special sectornumbers - - for (byte k = 0; k < (sectorNumber > 31 ? 16 : 4); k++) // if sector > 31 is 16 blocks each sector i.e. mifare 4k else its 1k or 2k with 4 blocks each sector + private async Task ReadWriteAccessOnClassicSector(int sectorNumber, string aKey, string bKey, byte[] buffer) + { + if (readerDevice.IsConnected) { - DataBlock = new MifareClassicDataBlockModel( - (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - k); - - try + return await Task.Run(async () => { - var isAuth = readerDevice.MifareClassicLogin(aKey, 0, (byte)elatecSpecificSectorNumber); - - if (buffer == null || buffer.Length != 16) // Read Mode + if (readerDevice.IsTWN4LegicReader) { - var data = readerDevice.MifareClassicReadBlock((byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k)); - - if (data.Length > 1) + try { - DataBlock.Data = data; - DataBlock.IsAuthenticated = true; - Sector.IsAuthenticated = isAuth; - Sector.DataBlock.Add(DataBlock); + await readerDevice.SearchTagAsync(); } + catch { } + } - else // No Read Access Allowed, try bKey - { - isAuth = readerDevice.MifareClassicLogin(bKey, 1, (byte)elatecSpecificSectorNumber); + Sector = new MifareClassicSectorModel(); + + var elatecSpecificSectorNumber = sectorNumber > 31 ? (sectorNumber - 32) * 4 + 32 : sectorNumber; // elatec uses special sectornumbers - data = readerDevice.MifareClassicReadBlock(k); + for (byte k = 0; k < (sectorNumber > 31 ? 16 : 4); k++) // if sector > 31 is 16 blocks each sector i.e. mifare 4k else its 1k or 2k with 4 blocks each sector + { + DataBlock = new MifareClassicDataBlockModel( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + k); - if (data.Length > 1) + try + { + var isAuth = false; + + try { - DataBlock.Data = data; - DataBlock.IsAuthenticated = true; - Sector.IsAuthenticated = isAuth; - Sector.DataBlock.Add(DataBlock); + await readerDevice.MifareClassic_LoginAsync(aKey, 0, (byte)elatecSpecificSectorNumber); + isAuth = true; } - else + catch { - Sector.IsAuthenticated = false; - DataBlock.IsAuthenticated = false; // finally failed to read data + isAuth = false; } + + if (buffer == null || buffer.Length != 16 && isAuth) // Read Mode + { + try + { + var data = await readerDevice.MifareClassic_ReadBlockAsync((byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k)); + + if (data.Length > 1) + { + DataBlock.Data = data; + DataBlock.IsAuthenticated = true; + Sector.IsAuthenticated = isAuth; + Sector.DataBlock.Add(DataBlock); + } + } + catch // No Read Access Allowed, try bKey + { + try + { + await readerDevice.MifareClassic_LoginAsync(bKey, 1, (byte)elatecSpecificSectorNumber); + isAuth = true; + + var data = await readerDevice.MifareClassic_ReadBlockAsync((byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k)); + + if (data.Length > 1) + { + DataBlock.Data = data; + DataBlock.IsAuthenticated = true; + Sector.IsAuthenticated = isAuth; + Sector.DataBlock.Add(DataBlock); + } + } + catch + { + isAuth = false; + Sector.IsAuthenticated = false; + DataBlock.IsAuthenticated = false; // finally failed to read data + } + } + } // read Data + + else if (buffer != null && buffer.Length == 16) + { + try + { + await readerDevice.MifareClassic_WriteBlockAsync(buffer, k); + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; + } + } // write Data } - } // read Data + catch + { + return ERROR.IOError; // IO ElatecError + } + } - else if (buffer != null && buffer.Length == 16) + if (Sector.IsAuthenticated) { - return readerDevice.MifareClassicWriteBlock(buffer, k) == true ? ERROR.NoError : ERROR.AuthenticationError; - } // write Data - } - catch - { - return ERROR.IOError; // IO ElatecError - } + return ERROR.NoError; //NO ElatecError + } + + return ERROR.AuthenticationError; // Auth ElatecError + }); } - if(Sector.IsAuthenticated) + else { - return ERROR.NoError; //NO ElatecError + return ERROR.NotReadyError; } - - return ERROR.AuthenticationError; // Auth ElatecError } #endregion @@ -302,30 +414,58 @@ public override ERROR ReadMifareUltralightSinglePage(int _pageNo) /// /// /// ElatecError Level - public override ERROR GetMiFareDESFireChipAppIDs(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey) + public async override Task GetMiFareDESFireChipAppIDs(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey) { - if (DesfireChip == null) + if (readerDevice.IsConnected) { - DesfireChip = new MifareDesfireChipModel(); - } + return await Task.Run(async () => + { + uint[] appArr; - DesfireChip.AppList = new System.Collections.Generic.List(); - if (readerDevice.DesfireSelectApplication(0)) - { - DesfireChip.FreeMemory = readerDevice.GetDesfireFreeMemory() ?? 0; + if (DesfireChip == null) + { + DesfireChip = new MifareDesfireChipModel(); + } - var appArr = readerDevice.GetDesfireAppIDs(); + DesfireChip.AppList = new System.Collections.Generic.List(); - if (appArr != null) - { - foreach (var appid in appArr) + try { - DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); + await readerDevice.SearchTagAsync(); + await readerDevice.MifareDesfire_SelectApplicationAsync(0); + DesfireChip.FreeMemory = await readerDevice.MifareDesfire_GetFreeMemoryAsync(); } - } + catch + { + DesfireChip.FreeMemory = 0; + } + + try + { + appArr = await readerDevice.MifareDesfire_GetAppIDsAsync(); + + if (appArr != null) + { + foreach (var appid in appArr) + { + DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); + } + } + } + catch + { + return ERROR.AuthenticationError; + } + + return ERROR.NoError; + }); + } + + else + { + return ERROR.NotReadyError; } - return ERROR.NoError; } /// @@ -336,17 +476,36 @@ public override ERROR GetMiFareDESFireChipAppIDs(string _appMasterKey, DESFireKe /// /// /// - public override ERROR AuthToMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumber, int _appID) + public async override Task AuthToMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumber, int _appID) { - - if (readerDevice.DesfireSelectApplication((uint)_appID)) + if (readerDevice.IsConnected) { - return readerDevice.DesfireAuthenticate( - _applicationMasterKey, - (byte)_keyNumber, - (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), - 1) == true ? ERROR.NoError : ERROR.AuthenticationError; + if (readerDevice.IsTWN4LegicReader) + { + try + { + await readerDevice.SearchTagAsync(); + } + catch { } + } + + try + { + await readerDevice.MifareDesfire_SelectApplicationAsync((uint)_appID); + + await readerDevice.MifareDesfire_AuthenticateAsync( + _applicationMasterKey, + (byte)_keyNumber, + (byte)(int)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), + 1); + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; + } } + else { return ERROR.NotReadyError; @@ -362,34 +521,66 @@ public override ERROR AuthToMifareDesfireApplication(string _applicationMasterKe /// /// /// - public override ERROR GetMifareDesfireAppSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID) + public async override Task GetMifareDesfireAppSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID) { - if (readerDevice.DesfireSelectApplication((uint)_appID)) + if (readerDevice.IsConnected) { - if (readerDevice.GetDesFireKeySettings()) + return await Task.Run(async () => { - MaxNumberOfAppKeys = readerDevice.NumberOfKeys; - EncryptionType = (DESFireKeyType)Enum.Parse(typeof(DESFireKeyType), Enum.GetName(typeof(Elatec.NET.DESFireKeyType), readerDevice.KeyType)); - DesfireAppKeySetting = (DESFireKeySettings)readerDevice.KeySettings; + if (readerDevice.IsTWN4LegicReader) + { + try + { + await readerDevice.SearchTagAsync(); + } + catch { } + } - return ERROR.NoError; - } // Get Settings without authentication - else - { - if (readerDevice.DesfireAuthenticate(_applicationMasterKey, (byte)_keyNumberCurrent, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), 1)) + try { - MaxNumberOfAppKeys = readerDevice.NumberOfKeys; - EncryptionType = (DESFireKeyType)readerDevice.KeyType; - DesfireAppKeySetting = (DESFireKeySettings)readerDevice.KeySettings; + await readerDevice.MifareDesfire_SelectApplicationAsync((uint)_appID); - return ERROR.NoError; + try + { + var ks = await readerDevice.MifareDesfire_GetKeySettingsAsync(); + + MaxNumberOfAppKeys = (byte)ks.NumberOfKeys; + EncryptionType = (DESFireKeyType)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), Enum.GetName(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), ks.KeyType)); + DesfireAppKeySetting = (DESFireKeySettings)ks.AccessRights; + + return ERROR.NoError; + } // Get Settings without authentication + catch + { + try + { + await readerDevice.MifareDesfire_AuthenticateAsync(_applicationMasterKey, (byte)_keyNumberCurrent, (byte)(int)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), 1); + var ks = await readerDevice.MifareDesfire_GetKeySettingsAsync(); + + MaxNumberOfAppKeys = (byte)ks.NumberOfKeys; + EncryptionType = (DESFireKeyType)Enum.Parse(typeof(DESFireKeyType), Enum.GetName(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), ks.KeyType)); + DesfireAppKeySetting = (DESFireKeySettings)ks.AccessRights; + + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; + } + } // needs Auth } - return ERROR.AuthenticationError; - } // authenticate first + catch + { + return ERROR.AuthenticationError; + } + }); + } + else + { + return ERROR.NotReadyError; } - return ERROR.AuthenticationError; } /// @@ -403,79 +594,135 @@ public override ERROR GetMifareDesfireAppSettings(string _applicationMasterKey, /// /// /// - public override ERROR CreateMifareDesfireApplication(string _piccMasterKey, DESFireKeySettings _keySettingsTarget, + public async override Task CreateMifareDesfireApplication(string _piccMasterKey, DESFireKeySettings _keySettingsTarget, DESFireKeyType _keyTypePiccMasterKey, DESFireKeyType _keyTypeTargetApplication, int _maxNbKeys, int _appID, bool authenticateToPICCFirst = true) { - if (readerDevice.DesfireSelectApplication(0)) + if (readerDevice.IsConnected) { - if (readerDevice.DesfireAuthenticate(_piccMasterKey, 0x00, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypePiccMasterKey)), 1)) + if (readerDevice.IsTWN4LegicReader) { - if (readerDevice.DesfireCreateApplication( - (Elatec.NET.DESFireKeySettings)_keySettingsTarget, - (Elatec.NET.DESFireKeyType)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTargetApplication)), - _maxNbKeys, - _appID)) + try { - return ERROR.NoError; - } - else - { - return ERROR.AuthenticationError; + await readerDevice.SearchTagAsync(); } + catch { } } - else + + try { - if (readerDevice.DesfireCreateApplication((Elatec.NET.DESFireKeySettings)_keySettingsTarget, (Elatec.NET.DESFireKeyType)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTargetApplication)), _maxNbKeys, _appID)) + await readerDevice.MifareDesfire_SelectApplicationAsync(0); + + await readerDevice.MifareDesfire_CreateApplicationAsync( + (Elatec.NET.Cards.Mifare.DESFireAppAccessRights)_keySettingsTarget, + (Elatec.NET.Cards.Mifare.DESFireKeyType)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTargetApplication)), + _maxNbKeys, + _appID); + return ERROR.NoError; + } // free create ? + catch + { + try { + await readerDevice.MifareDesfire_AuthenticateAsync(_piccMasterKey, 0, (byte)(int)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypePiccMasterKey)), 1); + + await readerDevice.MifareDesfire_CreateApplicationAsync( + (Elatec.NET.Cards.Mifare.DESFireAppAccessRights)_keySettingsTarget, + (Elatec.NET.Cards.Mifare.DESFireKeyType)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTargetApplication)), + _maxNbKeys, + _appID); + return ERROR.NoError; - } - else + } // auth first ? + catch { return ERROR.AuthenticationError; } } } - return ERROR.IOError; - + + else + { + return ERROR.NotReadyError; + } + + } - public override ERROR ChangeMifareDesfireApplicationKey(string _applicationMasterKeyCurrent, int _keyNumberCurrent, DESFireKeyType _keyTypeCurrent, + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public async override Task ChangeMifareDesfireApplicationKey(string _applicationMasterKeyCurrent, int _keyNumberCurrent, DESFireKeyType _keyTypeCurrent, string _applicationMasterKeyTarget, int _keyNumberTarget, int selectedDesfireAppKeyVersionTargetAsIntint, DESFireKeyType _keyTypeTarget, int _appIDCurrent, int _appIDTarget, DESFireKeySettings keySettings, int keyVersion) { - if (readerDevice.DesfireSelectApplication((uint)_appIDCurrent)) + if (readerDevice.IsConnected) { - if (readerDevice.DesfireAuthenticate(_applicationMasterKeyCurrent, (byte)_keyNumberCurrent, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeCurrent)), 1)) + if (readerDevice.IsTWN4LegicReader) { - if (readerDevice.DesfireChangeKey( - _applicationMasterKeyCurrent, - _applicationMasterKeyTarget, - (byte)keyVersion, - _keyNumberCurrent == 0 ? (byte)keySettings : (byte)((byte)keySettings | 0xE0), - (byte)_keyNumberTarget, - 1, - (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTarget)))) + try { - if (readerDevice.DesfireAuthenticate(_applicationMasterKeyTarget, (byte)_keyNumberTarget, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTarget)), 1)) - { - readerDevice.DesfireChangeKeySettings((byte)keySettings, 0, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTarget))); - } + await readerDevice.SearchTagAsync(); + } + catch { } + } - return ERROR.NoError; + try + { + await readerDevice.MifareDesfire_SelectApplicationAsync((uint)_appIDCurrent); + + await readerDevice.MifareDesfire_AuthenticateAsync(_applicationMasterKeyCurrent, (byte)_keyNumberCurrent, (byte)(int)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeCurrent)), 1); + + if (_applicationMasterKeyCurrent == _applicationMasterKeyTarget) + { + await readerDevice.MifareDesfire_ChangeKeySettingsAsync( + (DESFireAppAccessRights)keySettings, + 0, + (Elatec.NET.Cards.Mifare.DESFireKeyType)Enum.Parse( + typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), + Enum.GetName(typeof(DESFireKeyType), _keyTypeTarget) + ) + ); } + else { - if (readerDevice.DesfireAuthenticate(_applicationMasterKeyTarget, (byte)_keyNumberTarget, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTarget)), 1)) - { - readerDevice.DesfireChangeKeySettings((byte)keySettings, 0, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTarget))); - } - - return ERROR.AuthenticationError; + await readerDevice.MifareDesfire_ChangeKeyAsync( + _applicationMasterKeyCurrent, + _applicationMasterKeyTarget, + (byte)keyVersion, + _keyNumberCurrent == 0 ? (byte)keySettings : (byte)((byte)keySettings | 0xE0), + (byte)_keyNumberTarget, + 1, + (Elatec.NET.Cards.Mifare.DESFireKeyType)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeTarget))); } + + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; } } - return ERROR.NotReadyError; + + else + { + return ERROR.NotReadyError; + } + + } /// @@ -485,34 +732,41 @@ public override ERROR ChangeMifareDesfireApplicationKey(string _applicationMaste /// /// /// - public override ERROR DeleteMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyTypePiccMasterKey, int _appID) + public async override Task DeleteMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyTypePiccMasterKey, uint _appID) { - if (readerDevice.DesfireSelectApplication((uint)_appID)) + if (readerDevice.IsConnected) { - if (readerDevice.DesfireAuthenticate(_applicationMasterKey, 0x00, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypePiccMasterKey)), 1)) + if (readerDevice.IsTWN4LegicReader) { - if (readerDevice.DesfireDeleteApplication((uint)_appID)) + try { - return ERROR.NoError; + await readerDevice.SearchTagAsync(); } - else + catch { - return ERROR.AuthenticationError; + return ERROR.NotReadyError; } } - else + + try { - if (readerDevice.DesfireDeleteApplication((uint)_appID)) - { - return ERROR.NoError; - } - else + if (await AuthToMifareDesfireApplication(_applicationMasterKey, _keyTypePiccMasterKey, 0, 0) == ERROR.NoError) { - return ERROR.AuthenticationError; + await readerDevice.MifareDesfire_DeleteApplicationAsync(_appID); } } + catch + { + return ERROR.AuthenticationError; + } + return ERROR.NoError; } - return ERROR.IOError; + + else + { + return ERROR.NotReadyError; + } + } /// @@ -523,8 +777,9 @@ public override ERROR DeleteMifareDesfireApplication(string _applicationMasterKe /// /// /// - public override ERROR DeleteMifareDesfireFile(string _applicationMasterKey, DESFireKeyType _keyType, int _appID, int _fileID) + public async override Task DeleteMifareDesfireFile(string _applicationMasterKey, DESFireKeyType _keyType, int _appID, int _fileID) { + /* if (readerDevice.DesfireSelectApplication((uint)_appID)) { if (readerDevice.DesfireAuthenticate(_applicationMasterKey, 0x00, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), 1)) @@ -539,6 +794,7 @@ public override ERROR DeleteMifareDesfireFile(string _applicationMasterKey, DESF } } } + */ return ERROR.NotReadyError; } @@ -550,23 +806,48 @@ public override ERROR DeleteMifareDesfireFile(string _applicationMasterKey, DESF /// /// /// - public override ERROR FormatDesfireCard(string _applicationMasterKey, DESFireKeyType _keyType) + public async override Task FormatDesfireCard(string _applicationMasterKey, DESFireKeyType _keyType) { - if (readerDevice.DesfireSelectApplication(0)) + if (readerDevice.IsConnected) { - if (readerDevice.DesfireAuthenticate(_applicationMasterKey, 0x00, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), 1)) + if (readerDevice.IsTWN4LegicReader) { - if (readerDevice.DesfireFormatTag()) + try { - return ERROR.NoError; + await readerDevice.SearchTagAsync(); + } + catch + { + return ERROR.NotReadyError; + } + } + + try + { + if (await AuthToMifareDesfireApplication(_applicationMasterKey, _keyType, 0, 0) == ERROR.NoError) + { + await readerDevice.MifareDesfire_FormatTagAsync(); } else { return ERROR.AuthenticationError; } } + + catch + { + return ERROR.AuthenticationError; + } + + return ERROR.NoError; } - return ERROR.NotReadyError; + + else + { + return ERROR.NotReadyError; + } + + } /// @@ -577,26 +858,52 @@ public override ERROR FormatDesfireCard(string _applicationMasterKey, DESFireKey /// /// /// - public override ERROR GetMifareDesfireFileList(string _applicationMasterKey, RFiDGear.DataAccessLayer.DESFireKeyType _keyType, int _keyNumberCurrent, int _appID) + public async override Task GetMifareDesfireFileList(string _applicationMasterKey, RFiDGear.DataAccessLayer.DESFireKeyType _keyType, int _keyNumberCurrent, int _appID) { - if (readerDevice.DesfireSelectApplication((uint)_appID)) + if (readerDevice.IsConnected) { - if (readerDevice.DesfireAuthenticate(_applicationMasterKey, (byte)_keyNumberCurrent, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), 1)) + if (readerDevice.IsTWN4LegicReader) { - var appids = readerDevice.GetDesfireFileIDs(); - if (appids != null) + try { - FileIDList = appids; - return ERROR.NoError; + await readerDevice.SearchTagAsync(); } - else + catch { } + } + + try + { + await readerDevice.MifareDesfire_SelectApplicationAsync((uint)_appID); + + try { - return ERROR.AuthenticationError; + await readerDevice.MifareDesfire_AuthenticateAsync(_applicationMasterKey, (byte)_keyNumberCurrent, (byte)(int)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), 1); + } // try to auth first. + catch + { + + } + + var fids = await readerDevice.MifareDesfire_GetFileIDsAsync(); + + if (fids != null) + { + FileIDList = fids; } } + catch + { + return ERROR.NotReadyError; + } + + return ERROR.NoError; + } + + else + { + return ERROR.NotReadyError; } - return ERROR.NotReadyError; } /// @@ -608,30 +915,52 @@ public override ERROR GetMifareDesfireFileList(string _applicationMasterKey, RFi /// /// /// - public override ERROR GetMifareDesfireFileSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID, int _fileNo) + public async override Task GetMifareDesfireFileSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID, int _fileNo) { - if (readerDevice.DesfireSelectApplication((uint)_appID)) + if (readerDevice.IsConnected) { - if (readerDevice.DesfireAuthenticate(_applicationMasterKey, (byte)_keyNumberCurrent, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), 1)) + if (readerDevice.IsTWN4LegicReader) { - var fileSettings = readerDevice.GetDesFireFileSettings((byte)_fileNo); - uint fileSize = 0x00000000; + try + { + await readerDevice.SearchTagAsync(); + } + catch { } + } + + try + { + await readerDevice.MifareDesfire_SelectApplicationAsync((uint)_appID); - for (uint i = 9; i >= 6; i--) + try { - fileSize = fileSize << 8; - fileSize |= (byte)(fileSettings[i]); + await readerDevice.MifareDesfire_AuthenticateAsync( + _applicationMasterKey, + (byte)_keyNumberCurrent, + (byte)(int)Enum.Parse(typeof(Elatec.NET.Cards.Mifare.DESFireKeyType), + Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyType)), + 1); + } // try to auth first. + catch + { + } + + var fileSettings = await readerDevice.MifareDesfire_GetFileSettingsAsync((byte)_fileNo); + if (fileSettings != null) { DesfireFileSettings = new DESFireFileSettings(); - DesfireFileSettings.FileType = fileSettings[2]; - DesfireFileSettings.comSett = fileSettings[3]; - DesfireFileSettings.dataFile.fileSize = fileSize; + DesfireFileSettings.FileType = (byte)fileSettings.FileType; + DesfireFileSettings.comSett = (byte)fileSettings.ComSett; + DesfireFileSettings.dataFile.fileSize = fileSettings.DataFileSetting.FileSize; DesfireFileSettings.accessRights = new byte[2]; - DesfireFileSettings.accessRights[0] = fileSettings[4]; - DesfireFileSettings.accessRights[1] = fileSettings[5]; + DesfireFileSettings.accessRights[0] |= (byte)fileSettings.accessRights.ReadKeyNo; + DesfireFileSettings.accessRights[0] |= (byte)(fileSettings.accessRights.WriteKeyNo << 4); + DesfireFileSettings.accessRights[1] |= (byte)(fileSettings.accessRights.ReadWriteKeyNo); + DesfireFileSettings.accessRights[1] |= (byte)(fileSettings.accessRights.ChangeKeyNo << 4); + return ERROR.NoError; } else @@ -639,9 +968,18 @@ public override ERROR GetMifareDesfireFileSettings(string _applicationMasterKey, return ERROR.AuthenticationError; } } + catch + { + return ERROR.NotReadyError; + } + } + + else + { + return ERROR.NotReadyError; } - return ERROR.AuthenticationError; + } /// @@ -661,46 +999,62 @@ public override ERROR GetMifareDesfireFileSettings(string _applicationMasterKey, /// /// /// - public override ERROR CreateMifareDesfireFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, FileType_MifareDesfireFileType _fileType, DESFireAccessRights _accessRights, EncryptionMode _encMode, + public async override Task CreateMifareDesfireFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, FileType_MifareDesfireFileType _fileType, DESFireAccessRights _accessRights, EncryptionMode _encMode, int _appID, int _fileNo, int _fileSize, int _minValue = 0, int _maxValue = 1000, int _initValue = 0, bool _isValueLimited = false, int _maxNbOfRecords = 100) { - try + if (readerDevice.IsConnected) { - if (readerDevice.DesfireSelectApplication((uint)_appID)) + try { - if (readerDevice.DesfireAuthenticate(_appMasterKey, (byte)0x00, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeAppMasterKey)), 1)) + if (await AuthToMifareDesfireApplication(_appMasterKey, _keyTypeAppMasterKey, 0, _appID) == ERROR.NoError) { - UInt16 accessRights = 0x0000; - accessRights |= (byte)((((byte)_accessRights.readAccess) & 0xF0) >> 4); - accessRights |= (byte)((((byte)_accessRights.writeAccess) & 0x0F)); - accessRights |= (byte)((((byte)_accessRights.readAndWriteAccess) & 0xF0) >> 4); //lsb, upper nibble - accessRights |= (byte)((((byte)_accessRights.changeAccess) & 0x0F)); //lsb , lower nibble - - if (readerDevice.DesfireCreateFile((byte)_fileNo, (byte)_fileType, (byte)_encMode, accessRights, (UInt32)_fileSize)) - { - return ERROR.NoError; - } - else + switch (_fileType) { - return ERROR.AuthenticationError; + case FileType_MifareDesfireFileType.StdDataFile: + var ar = new DESFireFileAccessRights + { + ReadKeyNo = (byte)_accessRights.readAccess, + WriteKeyNo = (byte)_accessRights.writeAccess, + ReadWriteKeyNo = (byte)_accessRights.readAndWriteAccess, + ChangeKeyNo = (byte)_accessRights.changeAccess + }; + + try + { + await readerDevice.MifareDesfire_CreateStdDataFileAsync( + (byte)_fileNo, + (DESFireFileType)_fileType, + (Elatec.NET.Cards.Mifare.EncryptionMode)_encMode, + ar, + (UInt32)_fileSize); + } + + catch + { + return ERROR.AuthenticationError; + } + + break; } } - else - { - return ERROR.AuthenticationError; - } + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + return ERROR.IOError; } - return ERROR.AuthenticationError; - + return ERROR.NoError; } - catch (Exception e) + + else { - LogWriter.CreateLogEntry(e, FacilityName); - return ERROR.IOError; + return ERROR.NotReadyError; } + + } /// @@ -719,7 +1073,7 @@ public override ERROR CreateMifareDesfireFile(string _appMasterKey, DESFireKeyTy /// /// /// - public override ERROR ReadMiFareDESFireChipFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, + public async override Task ReadMiFareDESFireChipFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, EncryptionMode _encMode, @@ -727,6 +1081,7 @@ public override ERROR ReadMiFareDESFireChipFile(string _appMasterKey, DESFireKey { try { + /* if (readerDevice.DesfireSelectApplication((uint)_appID)) { if (readerDevice.DesfireAuthenticate(_appReadKey, (byte)_readKeyNo, (byte)(int)Enum.Parse(typeof(Elatec.NET.DESFireKeyType), Enum.GetName(typeof(RFiDGear.DataAccessLayer.DESFireKeyType), _keyTypeAppReadKey)), 1)) @@ -747,18 +1102,18 @@ public override ERROR ReadMiFareDESFireChipFile(string _appMasterKey, DESFireKey return ERROR.AuthenticationError; } } - + */ return ERROR.AuthenticationError; } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); return ERROR.IOError; } } - public override ERROR WriteMiFareDESFireChipFile(string _cardMasterKey, DESFireKeyType _keyTypeCardMasterKey, + public async override Task WriteMiFareDESFireChipFile(string _cardMasterKey, DESFireKeyType _keyTypeCardMasterKey, string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, diff --git a/RFiDGear/DataAccessLayer/Remote/FromIO/ReaderDevice.cs b/RFiDGear/DataAccessLayer/Remote/FromIO/ReaderDevice.cs index cbb7c4b..fd05dbc 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromIO/ReaderDevice.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromIO/ReaderDevice.cs @@ -1,6 +1,9 @@ using RFiDGear.Model; using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; namespace RFiDGear.DataAccessLayer.Remote.FromIO { @@ -37,12 +40,12 @@ public static ReaderDevice Instance { if (instance == null) { - instance = new ElatecNetProvider(PortNumber); + instance = new ElatecNetProvider(); return instance; } else if (instance != null && !(instance is ElatecNetProvider)) { - instance = new ElatecNetProvider(PortNumber); + instance = new ElatecNetProvider(); return instance; } else @@ -66,18 +69,20 @@ public static ReaderDevice Instance private static object syncRoot = new object(); private static ReaderDevice instance; + public abstract bool IsConnected { get; } public static ReaderTypes Reader { get; set; } public static int PortNumber { get; set; } public MifareClassicSectorModel Sector { get; set; } public MifareClassicDataBlockModel DataBlock { get; set; } - public GenericChipModel GenericChip { get; set; } + public List GenericChip { get; set; } public MifareDesfireChipModel DesfireChip { get; set; } public MifareClassicChipModel ClassicChip { get; set; } public ReaderTypes ReaderProvider { get; set; } - public string ReaderUnitName { get; set; } + public abstract string ReaderUnitName { get; set; } + public abstract string ReaderUnitVersion { get; set; } public byte[] MifareClassicData { get; set; } public bool DataBlockSuccessfullyAuth { get; set; } public bool SectorSuccessfullyAuth { get; set; } @@ -90,21 +95,21 @@ public static ReaderDevice Instance public DESFireKeySettings DesfireAppKeySetting { get; set; } #region Common - public abstract ERROR Connect(); - public abstract ERROR ReadChipPublic(); + public abstract Task ConnectAsync(); + public abstract Task ReadChipPublic(); #endregion #region MifareClassic // Mifare Classic Method Definitions - public abstract ERROR ReadMifareClassicSingleSector(int sectorNumber, string aKey, string bKey); - public abstract ERROR WriteMifareClassicSingleSector(int sectorNumber, string _aKey, string _bKey, byte[] buffer); - public abstract ERROR WriteMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey, byte[] buffer); - public abstract ERROR WriteMifareClassicWithMAD(int _madApplicationID, int _madStartSector, + public abstract Task ReadMifareClassicSingleSector(int sectorNumber, string aKey, string bKey); + public abstract Task WriteMifareClassicSingleSector(int sectorNumber, string _aKey, string _bKey, byte[] buffer); + public abstract Task WriteMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey, byte[] buffer); + public abstract Task WriteMifareClassicWithMAD(int _madApplicationID, int _madStartSector, string _aKeyToUse, string _bKeyToUse, string _aKeyToWrite, string _bKeyToWrite, string _madAKeyToUse, string _madBKeyToUse, string _madAKeyToWrite, string _madBKeyToWrite, byte[] buffer, byte _madGPB, SectorAccessBits _sab, bool _useMADToAuth, bool _keyToWriteUseMAD); - public abstract ERROR ReadMifareClassicWithMAD(int madApplicationID, string _aKeyToUse, string _bKeyToUse, + public abstract Task ReadMifareClassicWithMAD(int madApplicationID, string _aKeyToUse, string _bKeyToUse, string _madAKeyToUse, string _madBKeyToUse, int _length, byte _madGPB, bool _useMADToAuth, bool _aiToUseIsMAD); #endregion @@ -115,24 +120,24 @@ public abstract ERROR ReadMifareClassicWithMAD(int madApplicationID, string _aKe #endregion #region MifareDesfire - public abstract ERROR GetMiFareDESFireChipAppIDs(string _appMasterKey = "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", DESFireKeyType _keyTypeAppMasterKey = DESFireKeyType.DF_KEY_DES); - public abstract ERROR CreateMifareDesfireFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, FileType_MifareDesfireFileType _fileType, DESFireAccessRights _accessRights, EncryptionMode _encMode, + public abstract Task GetMiFareDESFireChipAppIDs(string _appMasterKey = "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", DESFireKeyType _keyTypeAppMasterKey = DESFireKeyType.DF_KEY_DES); + public abstract Task CreateMifareDesfireFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, FileType_MifareDesfireFileType _fileType, DESFireAccessRights _accessRights, EncryptionMode _encMode, int _appID, int _fileNo, int _fileSize, int _minValue = 0, int _maxValue = 1000, int _initValue = 0, bool _isValueLimited = false, int _maxNbOfRecords = 100); - public abstract ERROR ReadMiFareDESFireChipFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, + public abstract Task ReadMiFareDESFireChipFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, EncryptionMode _encMode, int _fileNo, int _appID, int _fileSize); - public abstract ERROR WriteMiFareDESFireChipFile(string _cardMasterKey, DESFireKeyType _keyTypeCardMasterKey, + public abstract Task WriteMiFareDESFireChipFile(string _cardMasterKey, DESFireKeyType _keyTypeCardMasterKey, string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, EncryptionMode _encMode, int _fileNo, int _appID, byte[] _data); - public abstract ERROR AuthToMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumber, int _appID = 0); - public abstract ERROR GetMifareDesfireAppSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0); + public abstract Task AuthToMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumber, int _appID = 0); + public abstract Task GetMifareDesfireAppSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0); /// /// Creates a new Application @@ -142,17 +147,17 @@ public abstract ERROR WriteMiFareDESFireChipFile(string _cardMasterKey, DESFireK /// int max. number of keys /// int application id /// True if the Operation was successful, false otherwise - public abstract ERROR CreateMifareDesfireApplication(string _piccMasterKey, DESFireKeySettings _keySettingsTarget, DESFireKeyType _keyTypePiccMasterKey, DESFireKeyType _keyTypeTargetApplication, int _maxNbKeys, int _appID, bool authenticateToPICCFirst = true); + public abstract Task CreateMifareDesfireApplication(string _piccMasterKey, DESFireKeySettings _keySettingsTarget, DESFireKeyType _keyTypePiccMasterKey, DESFireKeyType _keyTypeTargetApplication, int _maxNbKeys, int _appID, bool authenticateToPICCFirst = true); - public abstract ERROR ChangeMifareDesfireApplicationKey(string _applicationMasterKeyCurrent, int _keyNumberCurrent, DESFireKeyType _keyTypeCurrent, + public abstract Task ChangeMifareDesfireApplicationKey(string _applicationMasterKeyCurrent, int _keyNumberCurrent, DESFireKeyType _keyTypeCurrent, string _applicationMasterKeyTarget, int _keyNumberTarget, int selectedDesfireAppKeyVersionTargetAsIntint, DESFireKeyType _keyTypeTarget, int _appIDCurrent, int _appIDTarget, DESFireKeySettings keySettings, int keyVersion); - public abstract ERROR DeleteMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _appID = 0); - public abstract ERROR DeleteMifareDesfireFile(string _applicationMasterKey, DESFireKeyType _keyType, int _appID = 0, int _fileID = 0); - public abstract ERROR FormatDesfireCard(string _applicationMasterKey, DESFireKeyType _keyType); - public abstract ERROR GetMifareDesfireFileList(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0); - public abstract ERROR GetMifareDesfireFileSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0, int _fileNo = 0); + public abstract Task DeleteMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, uint _appID = 0); + public abstract Task DeleteMifareDesfireFile(string _applicationMasterKey, DESFireKeyType _keyType, int _appID = 0, int _fileID = 0); + public abstract Task FormatDesfireCard(string _applicationMasterKey, DESFireKeyType _keyType); + public abstract Task GetMifareDesfireFileList(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0); + public abstract Task GetMifareDesfireFileSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0, int _fileNo = 0); #endregion diff --git a/RFiDGear/Model/Checkpoint.cs b/RFiDGear/Model/Checkpoint.cs index ea584e9..2485876 100644 --- a/RFiDGear/Model/Checkpoint.cs +++ b/RFiDGear/Model/Checkpoint.cs @@ -26,6 +26,23 @@ public Checkpoint() ErrorLevel = ERROR.Empty; } + public string CheckpointIndex { get; set; } + + public int CheckpointIndexAsInt + { + get { + int res; + if (int.TryParse(CheckpointIndex, out res)) + { + return res; + } + else + { + return 0; + } + } + } + public ERROR ErrorLevel { get; set; } public string TaskIndex { get; set; } diff --git a/RFiDGear/Model/GenericChipModel.cs b/RFiDGear/Model/GenericChipModel.cs index 698b0a4..bfeaed6 100644 --- a/RFiDGear/Model/GenericChipModel.cs +++ b/RFiDGear/Model/GenericChipModel.cs @@ -11,7 +11,6 @@ public class GenericChipModel { public GenericChipModel() { - } public GenericChipModel(string uid, CARD_TYPE cardType) @@ -20,29 +19,17 @@ public GenericChipModel(string uid, CARD_TYPE cardType) CardType = cardType; } - public GenericChipModel(string uid, CARD_TYPE cardType, string sak, string rats) + public GenericChipModel(GenericChipModel chip) { - UID = uid; - CardType = cardType; - SAK = sak; - RATS = rats; - } - - public GenericChipModel(string uid, CARD_TYPE cardType, string sak, string rats, string versionL4) - { - UID = uid; - CardType = cardType; - SAK = sak; - RATS = rats; - VersionL4 = versionL4; + this.UID = chip.UID; + this.CardType = chip.CardType; } public string UID { get; set; } public CARD_TYPE CardType { get; set; } - public string SAK { get; set; } - public string RATS { get; set; } - public string VersionL4 { get; set; } - public GenericChipModel Child { get; set; } - public GenericChipModel GrandChild { get; set; } + + public bool? HasChilds => Childs?.Count > 0; + + public List Childs { get; set; } } } \ No newline at end of file diff --git a/RFiDGear/Model/MifareClassic/MifareClassicChipModel.cs b/RFiDGear/Model/MifareClassic/MifareClassicChipModel.cs index dd6139b..d539ecc 100644 --- a/RFiDGear/Model/MifareClassic/MifareClassicChipModel.cs +++ b/RFiDGear/Model/MifareClassic/MifareClassicChipModel.cs @@ -24,6 +24,13 @@ public MifareClassicChipModel(string uid, CARD_TYPE cardType) UID = uid; } + public MifareClassicChipModel(GenericChipModel chip) + { + CardType = chip.CardType; + UID = chip.UID; + Childs = chip.Childs; + } + public uint FreeMemory { get; set; } } } \ No newline at end of file diff --git a/RFiDGear/Model/MifareDesfire/MifareDesfireChipModel.cs b/RFiDGear/Model/MifareDesfire/MifareDesfireChipModel.cs index 1b558e1..41e5d49 100644 --- a/RFiDGear/Model/MifareDesfire/MifareDesfireChipModel.cs +++ b/RFiDGear/Model/MifareDesfire/MifareDesfireChipModel.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System; +using Org.BouncyCastle.Bcpg; namespace RFiDGear.Model { @@ -42,17 +43,37 @@ public MifareDesfireChipModel(string uid, CARD_TYPE cardType) CardType = cardType; } - public MifareDesfireChipModel(GenericChipModel genericChip) + public MifareDesfireChipModel(string uid, CARD_TYPE cardType, string sak, string rats) + { + UID = uid; + CardType = cardType; + SAK = sak; + RATS = rats; + } + + public MifareDesfireChipModel(string uid, CARD_TYPE cardType, string sak, string rats, string versionL4) + { + UID = uid; + CardType = cardType; + SAK = sak; + RATS = rats; + VersionL4 = versionL4; + } + + public MifareDesfireChipModel(MifareDesfireChipModel genericChip) { UID = genericChip.UID; CardType = genericChip.CardType; - RATS = genericChip.RATS; SAK = genericChip.SAK; - L4Version = genericChip.VersionL4; - Child = genericChip.Child; + RATS = genericChip.RATS; + VersionL4 = genericChip.VersionL4; + Childs = genericChip.Childs; } - public string L4Version { get; set; } + public string SAK { get; set; } + public string RATS { get; set; } + public string VersionL4 { get; set; } + public uint FreeMemory { get; set; } } } \ No newline at end of file diff --git a/RFiDGear/Model/MifareUltralight/MifareUltralightChipModel.cs b/RFiDGear/Model/MifareUltralight/MifareUltralightChipModel.cs index 3375ff6..2096b8f 100644 --- a/RFiDGear/Model/MifareUltralight/MifareUltralightChipModel.cs +++ b/RFiDGear/Model/MifareUltralight/MifareUltralightChipModel.cs @@ -32,5 +32,11 @@ public MifareUltralightChipModel(string uid, CARD_TYPE cardType) CardType = cardType; UID = uid; } + + public MifareUltralightChipModel(GenericChipModel chip) + { + CardType = chip.CardType; + UID = chip.UID; + } } } \ No newline at end of file diff --git a/RFiDGear/Properties/AssemblyInfo.cs b/RFiDGear/Properties/AssemblyInfo.cs index cb93720..bce9144 100644 --- a/RFiDGear/Properties/AssemblyInfo.cs +++ b/RFiDGear/Properties/AssemblyInfo.cs @@ -11,9 +11,9 @@ [assembly: AssemblyTitle("RFiDGear")] [assembly: AssemblyDescription("RFiD Encoding Frontend")] [assembly: AssemblyConfiguration("x86")] -[assembly: AssemblyCompany("")] +[assembly: AssemblyCompany("Messgeraetetechnik Hansen")] [assembly: AssemblyProduct("RFiDGear")] -[assembly: AssemblyCopyright("Copyright 2023")] +[assembly: AssemblyCopyright("Copyright 2024")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // This sets the default COM visibility of types in the assembly to invisible. @@ -25,6 +25,6 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("1.7.*")] +[assembly: AssemblyVersion("1.8.*")] [assembly: Guid("a34bc413-e349-4fd1-8b90-2eb95a333436")] [assembly: NeutralResourcesLanguage("")] diff --git a/RFiDGear/RFiDGear.csproj b/RFiDGear/RFiDGear.csproj index 2697a68..523b242 100644 --- a/RFiDGear/RFiDGear.csproj +++ b/RFiDGear/RFiDGear.csproj @@ -8,10 +8,9 @@ WinExe RFiDGear RFiDGear - v4.8 + v4.8.1 Properties - False False False False @@ -100,6 +99,9 @@ RFiDGear.snk + + true + 4.0 @@ -362,13 +364,9 @@ ByteArray - {53fbd2f3-638e-4892-9f09-9a372c8f76d2} + {360f9af9-6717-45b6-9707-5974575fe96a} Elatec.NET - - {786d71e7-4d92-43e4-a9eb-4e07ffe36f70} - Log4CSharp - {ef56252e-257f-41d1-974b-c9015071ce7e} MVVMDialogs @@ -407,7 +405,7 @@ 1.9.1.8 - 2.5.0 + 3.0.0 7.0.0 diff --git a/RFiDGear/RFiDGear.csproj.user b/RFiDGear/RFiDGear.csproj.user index d9b23aa..80deecb 100644 --- a/RFiDGear/RFiDGear.csproj.user +++ b/RFiDGear/RFiDGear.csproj.user @@ -1,7 +1,8 @@  - REPORTTARGETPATH="D:\CardCheck_data\KP-000005-5_final.pdf" REPORTTEMPLATEFILE="D:\CardCheck_data\KP-000005-5_.pdf" CUSTOMPROJECTFILE="D:\CardCheck_data\KPruefung_Vorlagen\00_RFID_Gear_Vorlage\CardCheckAssistant_FreeMem.rfPrj" %24JOBNUMBER="KP-000005" %24CHIPNUMBER="5" AUTORUN=1 + + D:\CardCheck_Data @@ -16,7 +17,8 @@ D:\Seafile\Dokumente Privat\Steven\Projekte\Software\Windows\RFIDGear\RFiDGear\bin\Debug\ - "D:\Seafile\Dokumente Privat\Steven\Projekte\Software\Windows\RFIDGear\zipped.rfPrj" + + REPORTTARGETPATH="D:\CardCheck_data\KP-000005-5_final.pdf" REPORTTEMPLATEFILE="D:\CardCheck_data\KP-000005-5_.pdf" CUSTOMPROJECTFILE="D:\CardCheck_data\KPruefung_Vorlagen\00_RFID_Gear_Vorlage\CardCheckAssistant_FreeMem.rfPrj" %24JOBNUMBER="KP-000005" %24CHIPNUMBER="5" AUTORUN=1 diff --git a/RFiDGear/Resources/Manifest.de.resx b/RFiDGear/Resources/Manifest.de.resx index 5ab4c22..40ac47e 100644 --- a/RFiDGear/Resources/Manifest.de.resx +++ b/RFiDGear/Resources/Manifest.de.resx @@ -1087,7 +1087,7 @@ Wird benötigt von: Mifare Plus SL3 4K - + Mifare Desfire EV0 @@ -1511,4 +1511,154 @@ https://github.com/c3rebro/rfidgear Changelog + + Mifare Classic (alle) + + + Mifare Desfire + + + Mifare Plus (alle) + + + Mifare SAM (alle) + + + SmartMX Desfire (alle) + + + SmartMX MifareClassic 2K + + + Mifare Desfire EV0 1K + + + Mifare Desfire EV0 256 + + + Mifare Desfire EV0 2K + + + Mifare Desfire EV0 4K + + + Desfire EV0 1K (Emulated - SmartMX) + + + Desfire EV0 256 Bytes (Emulated - SmartMX) + + + Desfire EV0 2K (Emulated - SmartMX) + + + Desfire EV0 4K (Emulated - SmartMX) + + + Desfire EV1 1K (Emulated - SmartMX) + + + Desfire EV1 256 Bytes (Emulated - SmartMX) + + + Desfire EV1 2K (Emulated - SmartMX) + + + Desfire EV1 4K (Emulated - SmartMX) + + + Desfire EV1 8K (Emulated - SmartMX) + + + Desfire EV2 16K (Emulated - SmartMX) + + + Desfire EV2 1K (Emulated - SmartMX) + + + Desfire EV2 2K (Emulated - SmartMX) + + + Desfire EV2 32K (Emulated - SmartMX) + + + Desfire EV2 4K (Emulated - SmartMX) + + + Desfire EV2 8K (Emulated - SmartMX) + + + Desfire EV3 16K (Emulated - SmartMX) + + + Desfire EV3 1K (Emulated - SmartMX) + + + Desfire EV3 2K (Emulated - SmartMX) + + + Desfire EV3 32K (Emulated - SmartMX) + + + Desfire EV3 4K (Emulated - SmartMX) + + + Desfire EV3 8K (Emulated - SmartMX) + + + Mifare Ultralight C EV1 + + + NTAG 210 + + + NTAG 211 + + + NTAG 212 + + + NTAG 213 + + + NTAG 214 + + + NTAG 215 + + + NTAG 216 + + + NTAG 424 + + + NTAG 426 + + + Mifare Desfire (alle) + + + CP Nr. + + + Kopieren + + + Einfügen + + + BESCHÄFTIGT + + + LEERLAUF + + + UNBEKANNT + + + Fehler + + + Es konnte kein Leser gefunden werden + \ No newline at end of file diff --git a/RFiDGear/Resources/Manifest.en.resx b/RFiDGear/Resources/Manifest.en.resx index 5022ce9..6508b38 100644 --- a/RFiDGear/Resources/Manifest.en.resx +++ b/RFiDGear/Resources/Manifest.en.resx @@ -1077,7 +1077,7 @@ Needed by: Mifare Plus SL3 4K - + Mifare Desfire EV0 @@ -1489,4 +1489,154 @@ https://github.com/c3rebro/rfidgear Changelog + + Mifare Classic (all) + + + Mifare Desfire + + + Mifare Plus (all) + + + Mifare SAM (all) + + + SmartMX Desfire (all) + + + SmartMX MifareClassic 2K + + + Mifare Desfire EV0 1K + + + Mifare Desfire EV0 256 + + + Mifare Desfire EV0 2K + + + Mifare Desfire EV0 4K + + + Desfire EV0 1K (Emulated - SmartMX) + + + Desfire EV0 256 Bytes (Emulated - SmartMX) + + + Desfire EV0 2K (Emulated - SmartMX) + + + Desfire EV0 4K (Emulated - SmartMX) + + + Desfire EV1 1K (Emulated - SmartMX) + + + Desfire EV1 256 Bytes (Emulated - SmartMX) + + + Desfire EV1 2K (Emulated - SmartMX) + + + Desfire EV1 4K (Emulated - SmartMX) + + + Desfire EV1 8K (Emulated - SmartMX) + + + Desfire EV2 16K (Emulated - SmartMX) + + + Desfire EV2 1K (Emulated - SmartMX) + + + Desfire EV2 2K (Emulated - SmartMX) + + + Desfire EV2 32K (Emulated - SmartMX) + + + Desfire EV2 4K (Emulated - SmartMX) + + + Desfire EV2 8K (Emulated - SmartMX) + + + Desfire EV3 16K (Emulated - SmartMX) + + + Desfire EV3 1K (Emulated - SmartMX) + + + Desfire EV3 2K (Emulated - SmartMX) + + + Desfire EV3 32K (Emulated - SmartMX) + + + Desfire EV3 4K (Emulated - SmartMX) + + + Desfire EV3 8K (Emulated - SmartMX) + + + Mifare Ultralight C EV1 + + + NTAG 210 + + + NTAG 211 + + + NTAG 212 + + + NTAG 213 + + + NTAG 214 + + + NTAG 215 + + + NTAG 216 + + + NTAG 424 + + + NTAG 426 + + + Mifare Desfire (all) + + + CP Nr. + + + Copy + + + Paste + + + BUSY + + + IDLE + + + UNKNOWN + + + ReaderError + + + No Reader Found + \ No newline at end of file diff --git a/RFiDGear/View/MainWindow.xaml b/RFiDGear/View/MainWindow.xaml index 1b0d0be..a7a0265 100644 --- a/RFiDGear/View/MainWindow.xaml +++ b/RFiDGear/View/MainWindow.xaml @@ -5,7 +5,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:dal="clr-namespace:RFiDGear.DataAccessLayer" - xmlns:dlgs="clr-namespace:MvvmDialogs.Behaviors;assembly=MVVMDialogs" + xmlns:dlgs="clr-namespace:MVVMDialogs.Behaviors;assembly=MVVMDialogs" xmlns:local="clr-namespace:RFiDGear" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:RFiDGear.ViewModel" @@ -321,7 +321,6 @@ CanUserReorderColumns="True" CanUserSortColumns="True" ItemsSource="{Binding ChipTasks.TaskCollection}" - SelectedIndex="{Binding DataGridPosition}" SelectedItem="{Binding Path=DataContext.SelectedSetupViewModel, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" SelectionMode="Single" VirtualizingPanel.IsVirtualizing="True"> @@ -432,14 +431,17 @@ - + @@ -590,6 +592,61 @@ + + + + + + + + + + + + + + + + + + + diff --git a/RFiDGear/View/SettingsView/SettingsTabPages/TabPageMiscReaderSettingsView.xaml b/RFiDGear/View/SettingsView/SettingsTabPages/TabPageMiscReaderSettingsView.xaml index 60f7770..57b0438 100644 --- a/RFiDGear/View/SettingsView/SettingsTabPages/TabPageMiscReaderSettingsView.xaml +++ b/RFiDGear/View/SettingsView/SettingsTabPages/TabPageMiscReaderSettingsView.xaml @@ -89,7 +89,7 @@ HorizontalAlignment="Left" VerticalAlignment="Stretch" Content="{Binding LocalizationResourceSet, ConverterParameter=labelCheckForUpdatesOnStart, Converter={StaticResource Localization}}" - IsChecked="{Binding CheckOnStart, Mode=TwoWay}" /> + IsChecked="{Binding CheckOnStart, Mode=TwoWay}"/> diff --git a/RFiDGear/View/TaskViews/CommonTask/CommonTaskView.xaml b/RFiDGear/View/TaskViews/CommonTask/CommonTaskView.xaml index 42dc13c..0febc4e 100644 --- a/RFiDGear/View/TaskViews/CommonTask/CommonTaskView.xaml +++ b/RFiDGear/View/TaskViews/CommonTask/CommonTaskView.xaml @@ -6,7 +6,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:dal="clr-namespace:RFiDGear.DataAccessLayer" - xmlns:dlgs="clr-namespace:MvvmDialogs.Behaviors;assembly=MVVMDialogs" + xmlns:dlgs="clr-namespace:MVVMDialogs.Behaviors;assembly=MVVMDialogs" xmlns:local="clr-namespace:RFiDGear" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:v="clr-namespace:RFiDGear.View" diff --git a/RFiDGear/View/TaskViews/CommonTask/CommonTasksTabPages/TabPageLogicTaskView.xaml b/RFiDGear/View/TaskViews/CommonTask/CommonTasksTabPages/TabPageLogicTaskView.xaml index 2832e20..7acd427 100644 --- a/RFiDGear/View/TaskViews/CommonTask/CommonTasksTabPages/TabPageLogicTaskView.xaml +++ b/RFiDGear/View/TaskViews/CommonTask/CommonTasksTabPages/TabPageLogicTaskView.xaml @@ -243,17 +243,26 @@ CanUserSortColumns="False" ItemsSource="{Binding Checkpoints, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding SelectedCheckpoint, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> + + + + + + + @@ -208,6 +229,8 @@ @@ -228,6 +251,8 @@ @@ -248,6 +273,8 @@ @@ -266,9 +293,11 @@ diff --git a/RFiDGear/View/TaskViews/RFIDTasks/GenericChipTask/GenericChipTaskTabPages/TabPageBasicChipCheckUpView.xaml b/RFiDGear/View/TaskViews/RFIDTasks/GenericChipTask/GenericChipTaskTabPages/TabPageBasicChipCheckUpView.xaml index 9083ba9..aa5a642 100644 --- a/RFiDGear/View/TaskViews/RFIDTasks/GenericChipTask/GenericChipTaskTabPages/TabPageBasicChipCheckUpView.xaml +++ b/RFiDGear/View/TaskViews/RFIDTasks/GenericChipTask/GenericChipTaskTabPages/TabPageBasicChipCheckUpView.xaml @@ -28,7 +28,7 @@ HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> @@ -143,13 +147,15 @@ public RFiDChipChildLayerViewModel( new MenuItem() { Header = "Read Sector using default Configuration", - Command = null //_cmdReadSectorWithDefaults + Command = null, + Visibility = Visibility.Hidden }, new MenuItem() { Header = "Edit Authentication Settings and Modify Sector", - Command = null // _cmdEditAuthAndModifySector + Command = null, + Visibility = Visibility.Hidden } }; })); @@ -178,7 +184,7 @@ public RFiDChipChildLayerViewModel( _cardType = cardType; _parentUid = parentUID?.UID; - _cmdReadSectorWithDefaults = new RelayCommand(ReadSectorWithDefaults); + _cmdReadSectorWithDefaults = new AsyncRelayCommand(ReadSectorWithDefaults); _cmdEditAuthAndModifySector = new RelayCommand(ReadSectorWithCustoms); Application.Current.Dispatcher.BeginInvoke((Action)(() => @@ -188,13 +194,15 @@ public RFiDChipChildLayerViewModel( new MenuItem() { Header = "Read Sector using default Configuration", - Command = _cmdReadSectorWithDefaults + Command = _cmdReadSectorWithDefaults, + IsEnabled = false }, new MenuItem() { Header = "Edit Authentication Settings and Modify Sector", - Command = _cmdEditAuthAndModifySector + Command = _cmdEditAuthAndModifySector, + IsEnabled = false } }; })); @@ -226,8 +234,9 @@ public RFiDChipChildLayerViewModel(string _childNodeHeader) private List ContextMenuItems; - public void ReadSectorWithDefaults() + public async Task ReadSectorWithDefaults() { + await Parent.ExecuteClassicQuickCheckCommand.ExecuteAsync(this); } public void ReadSectorWithCustoms() @@ -290,6 +299,7 @@ public object SelectedItem set { selectedItem = value; + OnPropertyChanged(nameof(SelectedItem)); } } @@ -325,6 +335,15 @@ public bool IsSelected set { isSelected = value; + + if (ContextMenuItems != null) + { + foreach (MenuItem item in ContextMenuItems) + { + item.IsEnabled = value; + } + } + OnPropertyChanged(nameof(IsSelected)); } } @@ -461,26 +480,24 @@ public string ChildNodeHeader { get { - switch (_cardType) + switch ((CARD_TYPE)((short)_cardType & 0xF000)) { - case CARD_TYPE.Mifare1K: - case CARD_TYPE.MifarePlus_SL1_1K: - case CARD_TYPE.Mifare2K: - case CARD_TYPE.MifarePlus_SL1_2K: - case CARD_TYPE.Mifare4K: - case CARD_TYPE.MifarePlus_SL1_4K: + case CARD_TYPE.MifareClassic: childNodeHeader = string.Format("Sector: [{0}]", sectorModel.SectorNumber); break; case CARD_TYPE.MifareUltralight: childNodeHeader = string.Format("Page: {0}", pageModel.PageNumber); break; - default: - if(Enum.GetName(typeof(CARD_TYPE), _cardType).ToLower(CultureInfo.CurrentCulture).Contains("desfire")) - { - childNodeHeader = string.Format("AppID: {0}", appModel.appID); - } + case CARD_TYPE.DESFireEV0: + case CARD_TYPE.DESFireEV1: + case CARD_TYPE.DESFireEV2: + case CARD_TYPE.DESFireEV3: + childNodeHeader = string.Format("AppID: {0} (0x{1})", appModel.appID, appModel.appID.ToString("X8")); break; + + default: + return childNodeHeader; } return childNodeHeader; } @@ -549,21 +566,15 @@ public void LoadChildren() } break; - case CARD_TYPE.DESFire: + case CARD_TYPE.DESFireEV0: case CARD_TYPE.DESFireEV1: case CARD_TYPE.DESFireEV2: + case CARD_TYPE.DESFireEV3: { children.Add(new RFiDChipGrandChildLayerViewModel(new MifareDesfireFileModel(), this)); } break; - case CARD_TYPE.Unspecified: //TODO: Add Card Type "TASK_MF_Classic" for every type - for (var i = 0; i <= 3; i++) - { - children.Add(new RFiDChipGrandChildLayerViewModel(new MifareClassicDataBlockModel(0, i), new MifareClassicSetupViewModel())); - } - break; - default: break; } diff --git a/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipGrandChildLayerViewModel.cs b/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipGrandChildLayerViewModel.cs index e9512b4..58e30b8 100644 --- a/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipGrandChildLayerViewModel.cs +++ b/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipGrandChildLayerViewModel.cs @@ -1,6 +1,6 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using RFiDGear.DataAccessLayer; using RFiDGear.Model; using System; diff --git a/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipParentLayerViewModel.cs b/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipParentLayerViewModel.cs index d0640c8..cfbbdf1 100644 --- a/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipParentLayerViewModel.cs +++ b/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipParentLayerViewModel.cs @@ -2,7 +2,7 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using RFiDGear.DataAccessLayer.Remote.FromIO; using RFiDGear.DataAccessLayer; @@ -17,6 +17,7 @@ using System.Windows.Input; using System.Xml.Serialization; using System.Reflection; +using System.Threading.Tasks; namespace RFiDGear.ViewModel { @@ -32,10 +33,9 @@ public class RFiDChipParentLayerViewModel : ObservableObject private protected ObservableCollection dialogs; - //private readonly CARD_TYPE _CardType; private readonly List ContextMenuItems; - private readonly RelayCommand _cmdReadAllSectorsWithDefaultKeys; + private readonly AsyncRelayCommand _cmdReadAllSectorsWithDefaultKeys; private readonly RelayCommand _cmdReadAllPages; private readonly RelayCommand _cmdDeleteThisNode; @@ -100,25 +100,26 @@ public RFiDChipParentLayerViewModel(MifareClassicChipModel _uidModel, Observable mifareClassicUidModel = _uidModel; CardType = mifareClassicUidModel.CardType; - _cmdReadAllSectorsWithDefaultKeys = new RelayCommand(MifareClassicQuickCheck); + _cmdReadAllSectorsWithDefaultKeys = new AsyncRelayCommand(MifareClassicQuickCheck); _cmdDeleteThisNode = new RelayCommand(DeleteMeCommand); - ContextMenuItems = new List(); - ContextMenuItems.Add(new MenuItem() + ContextMenuItems = new List { - Header = ResourceLoader.GetResource("menuItemContextMenuParentNodeQuickCheck"), - Command = _cmdReadAllSectorsWithDefaultKeys, - ToolTip = new ToolTip() + new MenuItem() { - Content = ResourceLoader.GetResource("toolTipContextMenuParentNodeMifareClassicQuickCheck") + Header = ResourceLoader.GetResource("menuItemContextMenuParentNodeQuickCheck"), + Command = _cmdReadAllSectorsWithDefaultKeys, + ToolTip = new ToolTip() + { + Content = ResourceLoader.GetResource("toolTipContextMenuParentNodeMifareClassicQuickCheck") + } + }, + new MenuItem() + { + Header = ResourceLoader.GetResource("hierarchicalDataTemplateParentNodeContextMenuDeleteNode"), + Command = _cmdDeleteThisNode } - }); - - ContextMenuItems.Add(new MenuItem() - { - Header = ResourceLoader.GetResource("hierarchicalDataTemplateParentNodeContextMenuDeleteNode"), - Command = _cmdDeleteThisNode - }); + }; if (!isTask) @@ -130,14 +131,23 @@ public RFiDChipParentLayerViewModel(MifareClassicChipModel _uidModel, Observable if (mifareClassicUidModel != null) { + ParentNodeHeader = String.Format( + ResourceLoader.GetResource("hierarchicalDataTemplateParentNodeHeaderChipType") + + " {1}\n" + + "Uid: {0}", + mifareClassicUidModel.UID, + ResourceLoader.GetResource( + string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), CardType)))); + + if (mifareClassicUidModel.Childs != null) { - ParentNodeHeader = String.Format( - ResourceLoader.GetResource("hierarchicalDataTemplateParentNodeHeaderChipType") + - " {1}\n" + - "Uid: {0}", - mifareClassicUidModel.UID, - ResourceLoader.GetResource( - string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), CardType)))); + foreach (var chip in mifareClassicUidModel.Childs) + { + ParentNodeHeaderRed += + String.Format("\nHybridTag: {0}\nUID: {1}", + Enum.GetName(typeof(CARD_TYPE), chip.CardType), + chip.UID); + } } } @@ -150,7 +160,7 @@ public RFiDChipParentLayerViewModel(MifareDesfireChipModel _uidModel, Observable CardType = mifareDesfireUidModel.CardType; - var _cmdReadAppIds = new RelayCommand(MifareDesfireQuickCheck); + var _cmdReadAppIds = new AsyncRelayCommand(MifareDesfireQuickCheck); _cmdCreateApp = new RelayCommand(CreateApp); _cmdEraseDesfireCard = new RelayCommand(EraseDesfireCard); @@ -179,14 +189,18 @@ public RFiDChipParentLayerViewModel(MifareDesfireChipModel _uidModel, Observable ResourceLoader.GetResource( string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), CardType)))); - if (mifareDesfireUidModel.Child != null) + + if (mifareDesfireUidModel.Childs != null) { - ParentNodeHeaderRed += - String.Format("\nHybridTag: {0}\nUID: {1}", - Enum.GetName(typeof(CARD_TYPE), mifareDesfireUidModel.Child.CardType), - mifareDesfireUidModel.Child.UID); + foreach (var chip in mifareDesfireUidModel.Childs) + { + ParentNodeHeaderRed += + String.Format("\nHybridTag: {0}\nUID: {1}", + Enum.GetName(typeof(CARD_TYPE), chip.CardType), + chip.UID); + } } - + Children.Add( new RFiDChipChildLayerViewModel( string.Format("SAK: {0}", mifareDesfireUidModel.SAK))); @@ -197,7 +211,7 @@ public RFiDChipParentLayerViewModel(MifareDesfireChipModel _uidModel, Observable Children.Add( new RFiDChipChildLayerViewModel( - string.Format("VER.: {0}", mifareDesfireUidModel.L4Version))); + string.Format("VER.: {0}", mifareDesfireUidModel.VersionL4))); } @@ -285,227 +299,255 @@ public RFiDChipParentLayerViewModel(GenericChipModel _chipModel, ObservableColle [XmlIgnore] public List ContextMenu => ContextMenuItems; - private void MifareClassicQuickCheck() + /// + /// + /// + private async Task MifareClassicQuickCheck() + { + await MifareClassicQuickCheck(null); + } + + /// + /// + /// + private async Task MifareClassicQuickCheck(RFiDChipChildLayerViewModel chld) { - if (!isTask) + Mouse.OverrideCursor = Cursors.AppStarting; + + using (var device = ReaderDevice.Instance) { - using (var device = ReaderDevice.Instance) + foreach (var cnVM in Children) { - Mouse.OverrideCursor = Cursors.Wait; + cnVM.IsAuthenticated = null; + + if (chld != null) + { + if (!cnVM.IsSelected) + { + continue; + } + } - foreach (var cnVM in Children) + foreach (var key in settings.DefaultSpecification.MifareClassicDefaultQuickCheckKeys) { - foreach (var key in settings.DefaultSpecification.MifareClassicDefaultQuickCheckKeys) + if (cnVM.Children.Where(x => x.GrandChildNodeHeader == string.Format("Key: {0}", key)).Any()) { - if (device.ReadMifareClassicSingleSector(cnVM.SectorNumber, key, key) == ERROR.NoError) - { - cnVM.Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Key: {0}", key))); - cnVM.IsAuthenticated = true; - } - else - { - cnVM.IsAuthenticated = false; - continue; - } - break; + cnVM.Children.Remove(cnVM.Children.Where(x => x.GrandChildNodeHeader == string.Format("Key: {0}", key)).Single()); } - foreach (var gcVM in cnVM.Children.Where(x => x.MifareClassicDataBlock != null)) + if (await device.ReadMifareClassicSingleSector(cnVM.SectorNumber, key, key) == ERROR.NoError) { - if (device.Sector.DataBlock.Any(x => x.DataBlockNumberSectorBased == gcVM.DataBlockNumber)) // (gcVM.DataBlockContent != null) + cnVM.Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Key: {0}", key))); + cnVM.IsAuthenticated = true; + } + else + { + cnVM.IsAuthenticated = false; + continue; + } + break; + } + + foreach (var gcVM in cnVM.Children.Where(x => x.MifareClassicDataBlock != null)) + { + if (device.Sector.DataBlock.Any(x => x.DataBlockNumberSectorBased == gcVM.DataBlockNumber)) // (gcVM.DataBlockContent != null) + { + if (device.Sector.DataBlock.First(x => x.DataBlockNumberSectorBased == gcVM.DataBlockNumber).Data != null) { - if (device.Sector.DataBlock.First(x => x.DataBlockNumberSectorBased == gcVM.DataBlockNumber).Data != null) - { - gcVM.MifareClassicDataBlock.Data = device.Sector.DataBlock.First(x => x.DataBlockNumberSectorBased == gcVM.DataBlockNumber).Data; //device.currentSector[gcVM.DataBlockNumber]; - gcVM.IsAuthenticated = true; - } - else - { - gcVM.IsAuthenticated = false; - } + gcVM.MifareClassicDataBlock.Data = device.Sector.DataBlock.First(x => x.DataBlockNumberSectorBased == gcVM.DataBlockNumber).Data; //device.currentSector[gcVM.DataBlockNumber]; + gcVM.IsAuthenticated = true; } else { gcVM.IsAuthenticated = false; } } + else + { + gcVM.IsAuthenticated = false; + } } - - IsExpanded = true; - - Mouse.OverrideCursor = null; } + + IsExpanded = true; } + + Mouse.OverrideCursor = null; } - private void MifareDesfireQuickCheck() + /// + /// + /// + private async Task MifareDesfireQuickCheck() { - if (!isTask) + using (var device = ReaderDevice.Instance) { - using (var device = ReaderDevice.Instance) + if (device != null) { - if (device != null) - { - Mouse.OverrideCursor = Cursors.Wait; + Mouse.OverrideCursor = Cursors.AppStarting; - device.GetMifareDesfireAppSettings(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].EncryptionType); + await device.GetMifareDesfireAppSettings(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].EncryptionType); - uint[] appIDs = null; + uint[] appIDs = null; - if (device.GetMiFareDESFireChipAppIDs( - settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, - settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].EncryptionType) == ERROR.NoError) - { - appIDs = device?.DesfireChip?.AppIDs; - } + if (await device.GetMiFareDESFireChipAppIDs( + settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, + settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].EncryptionType) == ERROR.NoError) + { + appIDs = device?.DesfireChip?.AppIDs; + } - Children.Clear(); + Children.Clear(); - Children.Add( - new RFiDChipChildLayerViewModel( - string.Format("SAK: {0}", mifareDesfireUidModel.SAK))); + Children.Add( + new RFiDChipChildLayerViewModel( + string.Format("SAK: {0}", mifareDesfireUidModel.SAK))); - Children.Add( - new RFiDChipChildLayerViewModel( - string.Format("ATS: {0}", mifareDesfireUidModel.RATS))); + Children.Add( + new RFiDChipChildLayerViewModel( + string.Format("ATS: {0}", mifareDesfireUidModel.RATS))); - Children.Add( - new RFiDChipChildLayerViewModel( - string.Format("VER.: {0}", mifareDesfireUidModel.L4Version))); + Children.Add( + new RFiDChipChildLayerViewModel( + string.Format("VER.: {0}", mifareDesfireUidModel.VersionL4))); - Children.Add( - new RFiDChipChildLayerViewModel( - string.Format("Available Space: {0}Byte(s)", device.DesfireChip.FreeMemory))); + Children.Add( + new RFiDChipChildLayerViewModel( + string.Format("Available Space: {0}Byte(s)", device.DesfireChip.FreeMemory))); - Children.Add( - new RFiDChipChildLayerViewModel( - new MifareDesfireAppModel(0), this, CardType, dialogs)); - try + Children.Add( + new RFiDChipChildLayerViewModel( + new MifareDesfireAppModel(0), this, CardType, dialogs)); + try + { + if (appIDs != null) { - if (appIDs != null) + foreach (var appID in appIDs) { - foreach (var appID in appIDs) + if (appID == 0) { - if (appID == 0) - { - continue; - } + continue; + } - Children.Add(new RFiDChipChildLayerViewModel(new MifareDesfireAppModel(appID), this, CardType, dialogs)); + Children.Add(new RFiDChipChildLayerViewModel(new MifareDesfireAppModel(appID), this, CardType, dialogs)); - if (device.GetMifareDesfireAppSettings(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).Key, - settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).EncryptionType, - 0, (int)appID) == ERROR.NoError) - { - Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Available Keys: {0}", device.MaxNumberOfAppKeys))); - Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("App Encryption Type: {0}", Enum.GetName(typeof(DESFireKeyType), (device.EncryptionType))))); - Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Key Settings: {0}", Enum.GetName(typeof(DESFireKeySettings), (device.DesfireAppKeySetting & (DESFireKeySettings)0xF0))))); - - Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Change AMK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x01) == (DESFireKeySettings)0x01 ? "yes" : "no"))); - Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Listing without AMK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x02) == (DESFireKeySettings)0x02 ? "yes" : "no"))); - Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Create/Delete without AMK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x04) == (DESFireKeySettings)0x04 ? "yes" : "no"))); - Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Change Config: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x08) == (DESFireKeySettings)0x08 ? "yes" : "no"))); - } + if (await device.GetMifareDesfireAppSettings(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).Key, + settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).EncryptionType, + 0, (int)appID) == ERROR.NoError) + { + Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Available Keys: {0}", device.MaxNumberOfAppKeys))); + Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("App Encryption Type: {0}", Enum.GetName(typeof(DESFireKeyType), (device.EncryptionType))))); + Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Key Settings: {0}", Enum.GetName(typeof(DESFireKeySettings), (device.DesfireAppKeySetting & (DESFireKeySettings)0xF0))))); + + Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Change AMK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x01) == (DESFireKeySettings)0x01 ? "yes" : "no"))); + Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Listing without AMK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x02) == (DESFireKeySettings)0x02 ? "yes" : "no"))); + Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Create/Delete without AMK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x04) == (DESFireKeySettings)0x04 ? "yes" : "no"))); + Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Change Config: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x08) == (DESFireKeySettings)0x08 ? "yes" : "no"))); + } - //TODO: add grandchild fileid - if (device.GetMifareDesfireFileList( - settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).Key, - settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).EncryptionType, - 0, (int)appID) == ERROR.NoError) + //TODO: add grandchild fileid + if (await device.GetMifareDesfireFileList( + settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).Key, + settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).EncryptionType, + 0, (int)appID) == ERROR.NoError) + { + foreach (var fileID in device.FileIDList) { - foreach (var fileID in device.FileIDList) + Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(new MifareDesfireFileModel(null, fileID), Children.First(x => x.AppID == appID))); + + if (await device.GetMifareDesfireFileSettings(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).Key, + settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).EncryptionType, + 0, (int)appID, fileID) == ERROR.NoError) { - Children.First(x => x.AppID == appID).Children.Add(new RFiDChipGrandChildLayerViewModel(new MifareDesfireFileModel(null, fileID), Children.First(x => x.AppID == appID))); - - if (device.GetMifareDesfireFileSettings(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).Key, - settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings.First(x => x.KeyType == KeyType_MifareDesFireKeyType.DefaultDesfireCardApplicationMasterKey).EncryptionType, - 0, (int)appID, fileID) == ERROR.NoError) - { - var grandChild = Children.First(x => x.AppID == appID).Children.First(y => (y.DesfireFile != null ? y.DesfireFile.FileID : -1) == fileID); - - grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("FileType: {0}", Enum.GetName(typeof(FileType_MifareDesfireFileType), device.DesfireFileSettings.FileType)), grandChild)); - grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("FileSize: {0}Bytes", device.DesfireFileSettings.dataFile.fileSize.ToString(CultureInfo.CurrentCulture)), grandChild)); - grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("CommMode: {0}", Enum.GetName(typeof(EncryptionMode), device.DesfireFileSettings.comSett)), grandChild)); - grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("Read: {0}", Enum.GetName(typeof(TaskAccessRights), (device.DesfireFileSettings.accessRights[1] & 0xF0) >> 4)), grandChild)); - grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("Write: {0}", Enum.GetName(typeof(TaskAccessRights), device.DesfireFileSettings.accessRights[1] & 0x0F)), grandChild)); - grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("RW: {0}", Enum.GetName(typeof(TaskAccessRights), (device.DesfireFileSettings.accessRights[0] & 0xF0) >> 4)), grandChild)); //lsb, upper nibble - grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("Change: {0}", Enum.GetName(typeof(TaskAccessRights), device.DesfireFileSettings.accessRights[0] & 0x0F)), grandChild)); //lsb , lower nibble - } + var grandChild = Children.First(x => x.AppID == appID).Children.First(y => (y.DesfireFile != null ? y.DesfireFile.FileID : -1) == fileID); + + grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("FileType: {0}", Enum.GetName(typeof(FileType_MifareDesfireFileType), device.DesfireFileSettings.FileType)), grandChild)); + grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("FileSize: {0}Bytes", device.DesfireFileSettings.dataFile.fileSize.ToString(CultureInfo.CurrentCulture)), grandChild)); + grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("CommMode: {0}", Enum.GetName(typeof(EncryptionMode), device.DesfireFileSettings.comSett)), grandChild)); + grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("Read: {0}", Enum.GetName(typeof(TaskAccessRights), (device.DesfireFileSettings.accessRights[1] & 0xF0) >> 4)), grandChild)); + grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("Write: {0}", Enum.GetName(typeof(TaskAccessRights), device.DesfireFileSettings.accessRights[1] & 0x0F)), grandChild)); + grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("RW: {0}", Enum.GetName(typeof(TaskAccessRights), (device.DesfireFileSettings.accessRights[0] & 0xF0) >> 4)), grandChild)); //lsb, upper nibble + grandChild.Children.Add(new RFiDChipGrandGrandChildLayerViewModel(string.Format("Change: {0}", Enum.GetName(typeof(TaskAccessRights), device.DesfireFileSettings.accessRights[0] & 0x0F)), grandChild)); //lsb , lower nibble } } } } - else - { - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("Directory Listing NOT Allowed")); - } - } - - - catch - { - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("Undefined ERROR")); - } - - if (device.AuthToMifareDesfireApplication(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, DESFireKeyType.DF_KEY_AES, 0) == ERROR.NoError) - { - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("PICC MasterKey Set (32x \"0\" + AES)")); - } - else if (device.AuthToMifareDesfireApplication(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, DESFireKeyType.DF_KEY_3K3DES, 0) == ERROR.NoError) - { - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("PICC MasterKey Set (32x \"0\" + 3KDES)")); - } - else if (device.AuthToMifareDesfireApplication(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, DESFireKeyType.DF_KEY_DES, 0) == ERROR.NoError) - { - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("PICC MasterKey NOT Set (32x \"0\" + DES)")); } else { - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("PICC SECURED, MasterKey Unknown")); + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("Directory Listing NOT Allowed")); } + } - if (device.GetMifareDesfireAppSettings("00000000000000000000000000000000", DESFireKeyType.DF_KEY_AES, 0, 0) == ERROR.NoError || - device.GetMifareDesfireAppSettings("00000000000000000000000000000000", DESFireKeyType.DF_KEY_3K3DES, 0, 0) == ERROR.NoError || - device.GetMifareDesfireAppSettings("00000000000000000000000000000000", DESFireKeyType.DF_KEY_DES, 0, 0) == ERROR.NoError) - { - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Change PICC MK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x01) == (DESFireKeySettings)0x01 ? "yes" : "no"))); - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Listing without PICC MK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x02) == (DESFireKeySettings)0x02 ? "yes" : "no"))); - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Create/Delete without PICC MK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x04) == (DESFireKeySettings)0x04 ? "yes" : "no"))); - Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Change PICC Config: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x08) == (DESFireKeySettings)0x08 ? "yes" : "no"))); - } + catch + { + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("Undefined ERROR")); + } + + if (await device.AuthToMifareDesfireApplication(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, DESFireKeyType.DF_KEY_AES, 0) == ERROR.NoError) + { + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("PICC MasterKey Set (32x \"0\" + AES)")); + } + else if (await device.AuthToMifareDesfireApplication(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, DESFireKeyType.DF_KEY_3K3DES, 0) == ERROR.NoError) + { + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("PICC MasterKey Set (32x \"0\" + 3KDES)")); + } + else if (await device.AuthToMifareDesfireApplication(settings.DefaultSpecification.MifareDesfireDefaultSecuritySettings[0].Key, DESFireKeyType.DF_KEY_DES, 0) == ERROR.NoError) + { + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("PICC MasterKey NOT Set (32x \"0\" + DES)")); + } + else + { + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel("PICC SECURED, MasterKey Unknown")); + } - IsExpanded = true; + if (await device.GetMifareDesfireAppSettings("00000000000000000000000000000000", DESFireKeyType.DF_KEY_AES, 0, 0) == ERROR.NoError || + await device.GetMifareDesfireAppSettings("00000000000000000000000000000000", DESFireKeyType.DF_KEY_3K3DES, 0, 0) == ERROR.NoError || + await device.GetMifareDesfireAppSettings("00000000000000000000000000000000", DESFireKeyType.DF_KEY_DES, 0, 0) == ERROR.NoError) + { + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Change PICC MK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x01) == (DESFireKeySettings)0x01 ? "yes" : "no"))); + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Listing without PICC MK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x02) == (DESFireKeySettings)0x02 ? "yes" : "no"))); + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Create/Delete without PICC MK: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x04) == (DESFireKeySettings)0x04 ? "yes" : "no"))); + Children.First(x => x.AppID == 0).Children.Add(new RFiDChipGrandChildLayerViewModel(string.Format("Allow Change PICC Config: {0}", (device.DesfireAppKeySetting & (DESFireKeySettings)0x08) == (DESFireKeySettings)0x08 ? "yes" : "no"))); - Mouse.OverrideCursor = null; } + + IsExpanded = true; + + Mouse.OverrideCursor = null; } } + } + /// + /// + /// private void MifareUltralightQuickCheck() { if (!isTask) { using (var device = ReaderDevice.Instance) { - Mouse.OverrideCursor = Cursors.Wait; + Mouse.OverrideCursor = Cursors.AppStarting; foreach (var cnVM in Children) { if (device.ReadMifareUltralightSinglePage(cnVM.PageNumber) == ERROR.NoError) { - var dataToShow = ByteConverter.GetStringFrom(device.MifareUltralightPageData); - - for (var i = (ByteConverter.GetStringFrom(device.MifareUltralightPageData).Length) - 2; i > 0; i -= 2) + //var dataToShow = ByteArrayConverter.GetStringFrom(device.MifareUltralightPageData); + /* + for (var i = (ByteArrayConverter.GetStringFrom(device.MifareUltralightPageData).Length) - 2; i > 0; i -= 2) { dataToShow = dataToShow.Insert(i, " "); } - + */ cnVM.Children.Add( new RFiDChipGrandChildLayerViewModel( - string.Format("Data: {0}", dataToShow))); + //string.Format("Data: {0}", dataToShow))); + string.Format("Data: {0}", null))); cnVM.IsAuthenticated = true; } @@ -549,7 +591,7 @@ private void EraseDesfireCard() { using (var device = ReaderDevice.Instance) { - Mouse.OverrideCursor = Cursors.Wait; + Mouse.OverrideCursor = Cursors.AppStarting; IsExpanded = true; @@ -694,7 +736,7 @@ public CARD_TYPE CardType get => mifareClassicUidModel != null ? mifareClassicUidModel.CardType : (mifareDesfireUidModel != null ? mifareDesfireUidModel.CardType : (mifareUltralightUidModel != null ? mifareUltralightUidModel.CardType : - (genericChip != null ? genericChip.CardType : CARD_TYPE.Unspecified) + (genericChip != null ? genericChip.CardType : CARD_TYPE.NOTAG) )); set { @@ -801,12 +843,12 @@ public bool? IsBeingProgrammed /// /// /// - public ICommand ExecuteDesfireQuickCheckCommand => new RelayCommand(MifareDesfireQuickCheck); + public IAsyncRelayCommand ExecuteDesfireQuickCheckCommand => new AsyncRelayCommand(MifareDesfireQuickCheck); /// /// /// - public ICommand ExecuteClassicQuickCheckCommand => new RelayCommand(MifareClassicQuickCheck); + public IAsyncRelayCommand ExecuteClassicQuickCheckCommand => new AsyncRelayCommand((x) => MifareClassicQuickCheck(x)); /// /// @@ -820,6 +862,9 @@ public bool? IsBeingProgrammed #endregion + /// + /// + /// private void LoadChildren() { switch (CardType) diff --git a/RFiDGear/ViewModel/MainWindowViewModel.cs b/RFiDGear/ViewModel/MainWindowViewModel.cs index 8850ba3..b26c166 100644 --- a/RFiDGear/ViewModel/MainWindowViewModel.cs +++ b/RFiDGear/ViewModel/MainWindowViewModel.cs @@ -36,9 +36,9 @@ using System.Windows.Threading; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using Log4CSharp; + using MefMvvm.SharedContracts.ViewModel; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using RedCell.Diagnostics.Update; using RFiDGear.DataAccessLayer; using RFiDGear.DataAccessLayer.Remote.FromIO; @@ -52,9 +52,8 @@ namespace RFiDGear.ViewModel [ExportViewModel("MainWin")] public class MainWindowViewModel : ObservableObject { - private static readonly string FacilityName = "RFiDGear"; - private readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version; + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private readonly string[] args; private readonly Dictionary variablesFromArgs = new Dictionary(); private readonly Updater updater; @@ -64,9 +63,11 @@ public class MainWindowViewModel : ObservableObject private protected ReportReaderWriter reportReaderWriter; private protected DispatcherTimer triggerReadChip; private protected DispatcherTimer taskTimeout; + private protected Timer checkUpdate = null; + private protected Timer checkReader = null; private protected string reportOutputPath; private protected string reportTemplateFile; - private protected ChipTaskHandlerModel taskHandler; + private protected ChipTaskHandlerModel taskHandler; private protected List mifareClassicUidModels = new List(); private protected List mifareDesfireViewModels = new List(); private protected bool _runSelectedOnly; @@ -75,21 +76,24 @@ public class MainWindowViewModel : ObservableObject // set if task was completed; indicates greenlight to continue execution // if programming takes too long; quit the process private bool firstRun = true; - private bool _isLoadingProject = true; private bool userIsNotifiedForAvailableUpdate = false; - private bool updateIsAvailable = false; private protected Mutex mutex; // one reader, one instance - only - #region Events / Delegates - - #endregion - #region Constructors public MainWindowViewModel() { + IsReaderBusy = false; + + if (!EventLog.SourceExists(Assembly.GetEntryAssembly().GetName().Name)) + { + EventLog.CreateEventSource(new EventSourceCreationData(Assembly.GetEntryAssembly().GetName().Name, "Application")); + } + + eventLog.Source = Assembly.GetEntryAssembly().GetName().Name; + RunMutex(this, null); bool autoLoadLastUsedDB; @@ -142,7 +146,7 @@ public MainWindowViewModel() taskHandler = new ChipTaskHandlerModel(); - ReaderStatus = CurrentReader == "None" ? "" : "ready"; + ReaderStatus = ""; DateTimeStatusBar = ""; databaseReaderWriter = new DatabaseReaderWriter(); resLoader = new ResourceLoader(); @@ -159,6 +163,14 @@ public MainWindowViewModel() Command = GetAddEditCommand }); + rowContextMenuItems.Add(new MenuItem() + { + Header = ResourceLoader.GetResource("contextMenuItemAddNewTask"), + HorizontalContentAlignment = HorizontalAlignment.Center, + VerticalContentAlignment = VerticalAlignment.Center, + Command = GetAddEditCommand + }); + rowContextMenuItems.Add(new MenuItem() { Header = ResourceLoader.GetResource("contextMenuItemAddOrEditTask"), @@ -224,7 +236,6 @@ public MainWindowViewModel() Application.Current.MainWindow.Closing += new CancelEventHandler(CloseThreads); Application.Current.MainWindow.Activated += new EventHandler(LoadCompleted); - updater.NewVersionAvailable += new EventHandler(EnableUpdate); //reminder: any dialog boxes added in the constructor won't appear until DialogBehavior.DialogViewModels gets bound to the Dialogs collection. } @@ -250,25 +261,31 @@ public MainWindowViewModel() /// /// Expose translated strings from ResourceLoader /// - public string LocalizationResourceSet { get; set; } + public string LocalizationResourceSet + { + get; set; + } #endregion Localization #region Local Commands - public ICommand GetAddEditCommand => new RelayCommand(OnNewGetAddEditCommand); - private void OnNewGetAddEditCommand() + /// + /// + /// + public IAsyncRelayCommand GetAddEditCommand => new AsyncRelayCommand(OnNewGetAddEditCommand); + private async Task OnNewGetAddEditCommand() { switch (selectedSetupViewModel) { case CommonTaskViewModel _: - OnNewNewCreateReportTaskCommand(); + await OnNewNewCreateReportTaskCommand(); break; case GenericChipTaskViewModel _: - OnNewCreateGenericChipTaskCommand(); + await OnNewCreateGenericChipTaskCommand(); break; case MifareClassicSetupViewModel _: - OnNewCreateClassicTaskCommand(); + await OnNewCreateClassicTaskCommand(); break; case MifareDesfireSetupViewModel _: OnNewCreateDesfireTaskCommand(); @@ -279,12 +296,21 @@ private void OnNewGetAddEditCommand() } } - private void OpenLastProjectFile() + /// + /// + /// + /// + private async Task OpenLastProjectFile() { - OpenLastProjectFile(string.Empty); + await OpenLastProjectFile(string.Empty); } - private void OpenLastProjectFile(string projectFileToUse) + /// + /// + /// + /// + /// + private async Task OpenLastProjectFile(string projectFileToUse) { using (var settings = new SettingsReaderWriter()) { @@ -307,7 +333,7 @@ private void OpenLastProjectFile(string projectFileToUse) ChipTasks.TaskCollection.Clear(); } - databaseReaderWriter.ReadDatabase(lastUsedDBPath); + await databaseReaderWriter.ReadDatabase(lastUsedDBPath); foreach (var vm in databaseReaderWriter.TreeViewModel) { @@ -335,13 +361,13 @@ private void OpenLastProjectFile(string projectFileToUse) /// /// /// - private void UpdateChip(object sender, EventArgs args) + private async void UpdateChip(object sender, EventArgs args) { GenericChipModel GenericChip; + Mouse.OverrideCursor = Cursors.AppStarting; try { - Mouse.OverrideCursor = Cursors.AppStarting; //try to get singleton instance using (var device = ReaderDevice.Instance) @@ -349,12 +375,12 @@ private void UpdateChip(object sender, EventArgs args) //reader was ready - proceed if (device != null) { - ReaderStatus = "busy"; - device.ReadChipPublic(); + IsReaderBusy = true; + await device.ReadChipPublic(); - GenericChip = device.GenericChip; + GenericChip = device.GenericChip[0]; - ReaderStatus = "ready"; + IsReaderBusy = false; ; } else { @@ -371,19 +397,18 @@ private void UpdateChip(object sender, EventArgs args) } // fill treeview with dummy models and viewmodels - OnNewReadChipCommand(); - OnNewResetTaskStatusCommand(); - OnNewWriteToChipOnceCommand(); + await ReadChipCommand.ExecuteAsync(null); + await ResetTaskStatusCommand.ExecuteAsync(null); + await WriteToChipOnceCommand.ExecuteAsync(null); } - Mouse.OverrideCursor = null; } catch (Exception e) { - Mouse.OverrideCursor = null; - - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } + + Mouse.OverrideCursor = null; } /// @@ -421,10 +446,10 @@ private void OnNewRemoveChipsFromTreeCommand() /// /// Show Detailed Version Info /// - public ICommand ShowChangeLogCommand => new RelayCommand(OnNewShowChangeLogCommand); - private void OnNewShowChangeLogCommand() + public IAsyncRelayCommand ShowChangeLogCommand => new AsyncRelayCommand(OnNewShowChangeLogCommand); + private async Task OnNewShowChangeLogCommand() { - AskForUpdateNow(true); + await AskForUpdateNow(true); } /// @@ -436,7 +461,7 @@ private void OnNewNewAboutDialogCommand() Dialogs.Add(new AboutViewModel() { Caption = ResourceLoader.GetResource("windowCaptionAboutRFiDGear"), - AboutText = string.Format("RFiDGear {0}.{1}.{2} {3}\n\n", Version.Major, Version.Minor, Version.Build, Constants.TITLE_SUFFIX) + AboutText = string.Format("RFiDGear {0}.{1}.{2} {3}\n\n", Version.Major, Version.Minor, Version.Build, RFiDGear.DataAccessLayer.Constants.TITLE_SUFFIX) + ResourceLoader.GetResource("textBoxTextAboutRFiDGear"), OnOk = (sender) => @@ -455,9 +480,10 @@ private void OnNewNewAboutDialogCommand() /// /// Create a new "Common" Task of Type "Report Creator" /// - public ICommand CreateGenericChipTaskCommand => new RelayCommand(OnNewCreateGenericChipTaskCommand); - private void OnNewCreateGenericChipTaskCommand() + public IAsyncRelayCommand CreateGenericChipTaskCommand => new AsyncRelayCommand(OnNewCreateGenericChipTaskCommand); + private async Task OnNewCreateGenericChipTaskCommand() { + var timerState = triggerReadChip.IsEnabled; triggerReadChip.IsEnabled = false; Mouse.OverrideCursor = Cursors.AppStarting; @@ -473,11 +499,11 @@ private void OnNewCreateGenericChipTaskCommand() { Caption = ResourceLoader.GetResource("windowCaptionAddEditGenericChipTask"), - OnOk = (sender) => + OnOk = async (sender) => { if (sender.SelectedTaskType == TaskType_GenericChipTask.ChangeDefault) { - sender.Settings.SaveSettings(); + await sender.SaveSettings.ExecuteAsync(null); } if (sender.SelectedTaskType == TaskType_GenericChipTask.ChipIsOfType || @@ -496,12 +522,14 @@ private void OnNewCreateGenericChipTaskCommand() OnPropertyChanged(nameof(ChipTasks)); } sender.Close(); + mw.Activate(); }, OnCancel = (sender) => { sender.Close(); + mw.Activate(); }, @@ -512,17 +540,24 @@ private void OnNewCreateGenericChipTaskCommand() OnCloseRequest = (sender) => { sender.Close(); + mw.Activate(); } }); } + + else + { + OnNewNoReaderFoundDialog(); + } } } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); dialogs.Clear(); + } Mouse.OverrideCursor = null; @@ -535,9 +570,11 @@ private void OnNewCreateGenericChipTaskCommand() /// /// Create a new "Common" Task of Type "Report Creator" /// - public ICommand CreateGenericTaskCommand => new RelayCommand(OnNewNewCreateReportTaskCommand); - private void OnNewNewCreateReportTaskCommand() + public IAsyncRelayCommand CreateGenericTaskCommand => new AsyncRelayCommand(OnNewNewCreateReportTaskCommand); + private async Task OnNewNewCreateReportTaskCommand() { + + var timerState = triggerReadChip.IsEnabled; triggerReadChip.IsEnabled = false; @@ -549,7 +586,7 @@ private void OnNewNewCreateReportTaskCommand() dialogs.Add(new CommonTaskViewModel(SelectedSetupViewModel, ChipTasks.TaskCollection, dialogs) { Caption = ResourceLoader.GetResource("windowCaptionAddEditGenericTask"), - + OnOk = (sender) => { @@ -569,12 +606,14 @@ private void OnNewNewCreateReportTaskCommand() OnPropertyChanged(nameof(ChipTasks)); } sender.Close(); + mw.Activate(); }, OnCancel = (sender) => { sender.Close(); + mw.Activate(); }, @@ -585,15 +624,18 @@ private void OnNewNewCreateReportTaskCommand() OnCloseRequest = (sender) => { sender.Close(); + mw.Activate(); } }); } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); dialogs.Clear(); + + } Mouse.OverrideCursor = null; @@ -606,9 +648,11 @@ private void OnNewNewCreateReportTaskCommand() /// /// Creates a new Task of Type Mifare Classic Card /// - public ICommand CreateClassicTaskCommand => new RelayCommand(OnNewCreateClassicTaskCommand); - private void OnNewCreateClassicTaskCommand() + public IAsyncRelayCommand CreateClassicTaskCommand => new AsyncRelayCommand(OnNewCreateClassicTaskCommand); + private async Task OnNewCreateClassicTaskCommand() { + + var timerState = triggerReadChip.IsEnabled; triggerReadChip.IsEnabled = false; @@ -631,7 +675,7 @@ private void OnNewCreateClassicTaskCommand() { if (sender.SelectedTaskType == TaskType_MifareClassicTask.ChangeDefault) { - sender.Settings.SaveSettings(); + sender.SaveSettings.ExecuteAsync(null); } if (sender.SelectedTaskType == TaskType_MifareClassicTask.WriteData || @@ -651,12 +695,19 @@ private void OnNewCreateClassicTaskCommand() OnPropertyChanged(nameof(ChipTasks)); } sender.Close(); + mw.Activate(); }, + OnUpdateStatus = (sender) => + { + IsReaderBusy = sender; + }, + OnCancel = (sender) => { sender.Close(); + mw.Activate(); }, @@ -667,17 +718,25 @@ private void OnNewCreateClassicTaskCommand() OnCloseRequest = (sender) => { sender.Close(); + mw.Activate(); } }); } + + else + { + OnNewNoReaderFoundDialog(); + } } } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); dialogs.Clear(); + + } Mouse.OverrideCursor = null; @@ -688,8 +747,8 @@ private void OnNewCreateClassicTaskCommand() /// /// /// - public ICommand CreateDesfireTaskCommand => new RelayCommand(OnNewCreateDesfireTaskCommand); - private void OnNewCreateDesfireTaskCommand() + public IAsyncRelayCommand CreateDesfireTaskCommand => new AsyncRelayCommand(OnNewCreateDesfireTaskCommand); + private async Task OnNewCreateDesfireTaskCommand() { var timerState = triggerReadChip.IsEnabled; @@ -709,7 +768,7 @@ private void OnNewCreateDesfireTaskCommand() { if (sender.SelectedTaskType == TaskType_MifareDesfireTask.ChangeDefault) { - sender.Settings.SaveSettings(); + sender.SaveSettings.ExecuteAsync(null); } if (sender.SelectedTaskType == TaskType_MifareDesfireTask.FormatDesfireCard || @@ -737,23 +796,36 @@ private void OnNewCreateDesfireTaskCommand() OnPropertyChanged(nameof(ChipTasks)); sender.Close(); + mw.Activate(); } }, + OnUpdateStatus = (sender) => + { + IsReaderBusy = sender; + }, + OnCancel = (sender) => { sender.Close(); + mw.Activate(); }, OnCloseRequest = (sender) => { sender.Close(); + mw.Activate(); } }); } + + else + { + OnNewNoReaderFoundDialog(); + } } Mouse.OverrideCursor = null; @@ -768,6 +840,7 @@ private void OnNewCreateDesfireTaskCommand() private void OnNewCreateUltralightTaskCommand() { + var timerState = triggerReadChip.IsEnabled; triggerReadChip.IsEnabled = false; @@ -805,6 +878,7 @@ private void OnNewCreateUltralightTaskCommand() OnPropertyChanged(nameof(ChipTasks)); sender.Close(); + mw.Activate(); } }, @@ -812,12 +886,14 @@ private void OnNewCreateUltralightTaskCommand() OnCancel = (sender) => { sender.Close(); + mw.Activate(); }, OnCloseRequest = (sender) => { sender.Close(); + mw.Activate(); } }); @@ -832,234 +908,201 @@ private void OnNewCreateUltralightTaskCommand() /// /// /// - public ICommand ExecuteQuickCheckCommand => new RelayCommand(OnNewExecuteQuickCheckCommand); - private void OnNewExecuteQuickCheckCommand() + public IAsyncRelayCommand ExecuteQuickCheckCommand => new AsyncRelayCommand(OnNewExecuteQuickCheckCommand); + private async Task OnNewExecuteQuickCheckCommand() { try { - Mouse.OverrideCursor = Cursors.Wait; + Mouse.OverrideCursor = Cursors.AppStarting; - ReadChipCommand.Execute(null); + await ReadChipCommand.ExecuteAsync(null); - if (treeViewParentNodes != null && treeViewParentNodes.Any(x => x.IsSelected) && treeViewParentNodes.Count > 0) + IsReaderBusy = true; + Mouse.OverrideCursor = Cursors.AppStarting; + + if (treeViewParentNodes != null && treeViewParentNodes.Any(x => x.IsSelected)) { - treeViewParentNodes.FirstOrDefault().IsSelected = true; + treeViewParentNodes.FirstOrDefault(x => x.IsSelected).IsExpanded = true; - if (treeViewParentNodes.Single(x => x.IsSelected == true).CardType == CARD_TYPE.Mifare1K || - treeViewParentNodes.Single(x => x.IsSelected == true).CardType == CARD_TYPE.Mifare2K || - treeViewParentNodes.Single(x => x.IsSelected == true).CardType == CARD_TYPE.Mifare4K) + if (((int)treeViewParentNodes.Single(x => x.IsSelected == true).CardType & 0xF000) == (int)CARD_TYPE.MifareClassic) { - treeViewParentNodes.Single(x => x.IsSelected == true).ExecuteClassicQuickCheckCommand.Execute(null); + await treeViewParentNodes.Single(x => x.IsSelected == true).ExecuteClassicQuickCheckCommand.ExecuteAsync(null); } // Mifare Classic else if (Enum.GetName(typeof(CARD_TYPE), treeViewParentNodes.Single(x => x.IsSelected == true).CardType).ToLower(CultureInfo.CurrentCulture).Contains("desfire")) { - treeViewParentNodes.Single(x => x.IsSelected == true).ExecuteDesfireQuickCheckCommand.Execute(null); + await treeViewParentNodes.Single(x => x.IsSelected == true).ExecuteDesfireQuickCheckCommand.ExecuteAsync(null); } // Mifare Desfire } + IsReaderBusy = false; Mouse.OverrideCursor = null; } catch { Mouse.OverrideCursor = null; } + + } /// /// /// - public ICommand ReadChipCommand => new RelayCommand(OnNewReadChipCommand); - private void OnNewReadChipCommand() + public IAsyncRelayCommand ReadChipCommand => new AsyncRelayCommand(OnNewReadChipCommand); + private async Task OnNewReadChipCommand() { var timerState = triggerReadChip.IsEnabled; - triggerReadChip.IsEnabled = false; - Mouse.OverrideCursor = Cursors.Wait; - ReaderStatus = "busy"; + Mouse.OverrideCursor = Cursors.AppStarting; + + if (ReaderDevice.Instance == null) + { + Mouse.OverrideCursor = null; + + return; + } + + IsReaderBusy = true; using (var device = ReaderDevice.Instance) { foreach (var item in treeViewParentNodes) { item.IsExpanded = false; + item.IsSelected = false; } - if (device?.ReadChipPublic() == ERROR.NoError && - !treeViewParentNodes.Any(x => x.UID == device.GenericChip.UID)) + device?.GenericChip?.Clear(); + var result = await device?.ReadChipPublic(); + var wellKnownTvNodes = from nodes in treeViewParentNodes from chips in device.GenericChip where nodes.UID == chips.UID select nodes; + + if (result == ERROR.NoError && !wellKnownTvNodes.Any()) { - // fill treeview with dummy models and viewmodels - switch (device.GenericChip.CardType) + foreach (var gCM in device.GenericChip) { - case CARD_TYPE.Mifare1K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.Mifare1K), Dialogs, false)); - break; - - case CARD_TYPE.Mifare2K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.Mifare2K), Dialogs, false)); - break; - - case CARD_TYPE.Mifare4K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.Mifare4K), Dialogs, false)); - break; - - case CARD_TYPE.DESFire: - case CARD_TYPE.DESFireEV1: - case CARD_TYPE.DESFireEV2: - case CARD_TYPE.DESFireEV3: - case CARD_TYPE.DESFire_256: - case CARD_TYPE.DESFire_2K: - case CARD_TYPE.DESFire_4K: - case CARD_TYPE.DESFireEV1_256: - case CARD_TYPE.DESFireEV1_2K: - case CARD_TYPE.DESFireEV1_4K: - case CARD_TYPE.DESFireEV1_8K: - case CARD_TYPE.DESFireEV2_2K: - case CARD_TYPE.DESFireEV2_4K: - case CARD_TYPE.DESFireEV2_8K: - case CARD_TYPE.DESFireEV2_16K: - case CARD_TYPE.DESFireEV2_32K: - case CARD_TYPE.DESFireEV3_2K: - case CARD_TYPE.DESFireEV3_4K: - case CARD_TYPE.DESFireEV3_8K: - case CARD_TYPE.DESFireEV3_16K: - case CARD_TYPE.DESFireEV3_32K: - case CARD_TYPE.SmartMX_DESFire_Generic: - case CARD_TYPE.SmartMX_DESFire_2K: - case CARD_TYPE.SmartMX_DESFire_4K: - case CARD_TYPE.SmartMX_DESFire_8K: - case CARD_TYPE.SmartMX_DESFire_16K: - case CARD_TYPE.SmartMX_DESFire_32K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareDesfireChipModel(device.GenericChip), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus_SL1_1K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.MifarePlus_SL1_1K), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus_SL1_2K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.MifarePlus_SL1_2K), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus_SL1_4K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.MifarePlus_SL1_4K), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus_SL2_1K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.MifarePlus_SL2_1K), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus_SL2_2K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.MifarePlus_SL2_2K), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus_SL2_4K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.MifarePlus_SL2_4K), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus_SL3_1K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.MifarePlus_SL3_1K), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus_SL3_2K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.MifarePlus_SL3_2K), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus_SL3_4K: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareClassicChipModel(device.GenericChip.UID, CARD_TYPE.MifarePlus_SL3_4K), Dialogs, false)); - break; - - case CARD_TYPE.MifareUltralight: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareUltralightChipModel(device.GenericChip.UID, device.GenericChip.CardType), Dialogs, false)); - break; - + switch ((CARD_TYPE)((short)gCM.CardType & 0xF000)) + { + case CARD_TYPE.MifareClassic: + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new MifareClassicChipModel(gCM as MifareClassicChipModel), Dialogs, false)); + break; - case CARD_TYPE.GENERIC_T_CL_A: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new MifareDesfireChipModel(device.GenericChip.UID, device.GenericChip.CardType), Dialogs, false)); - break; + case CARD_TYPE.DESFireEV0: + case CARD_TYPE.DESFireEV1: + case CARD_TYPE.DESFireEV2: + case CARD_TYPE.DESFireEV3: + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new MifareDesfireChipModel(gCM as MifareDesfireChipModel), Dialogs, false)); + break; - case CARD_TYPE.ISO15693: + case CARD_TYPE.MifarePlus: + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new MifareClassicChipModel(gCM as MifareClassicChipModel), Dialogs, false)); + break; - break; + case CARD_TYPE.MifareUltralight: + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new MifareUltralightChipModel(gCM), Dialogs, false)); + break; - default: - treeViewParentNodes.Add(new RFiDChipParentLayerViewModel(new GenericChipModel(device.GenericChip.UID, device.GenericChip.CardType), Dialogs, false)); - break; + default: + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new GenericChipModel(gCM), Dialogs, false)); + break; + } } - - + // fill treeview with dummy models and viewmodels } - else if (treeViewParentNodes.Any(x => x.UID == device?.GenericChip?.UID)) + else if (wellKnownTvNodes.Any()) { - treeViewParentNodes.First(x => x.UID == device.GenericChip.UID).IsSelected = true; + //wellKnownTvNodes.FirstOrDefault().IsExpanded = true; + wellKnownTvNodes.FirstOrDefault().IsSelected = true; } } Mouse.OverrideCursor = null; - ReaderStatus = "ready"; + IsReaderBusy = false; triggerReadChip.IsEnabled = timerState; + + } /// /// Reset all Task status information /// - public ICommand ResetTaskStatusCommand => new RelayCommand(OnNewResetTaskStatusCommand); - private void OnNewResetTaskStatusCommand() + public IAsyncRelayCommand ResetTaskStatusCommand => new AsyncRelayCommand(OnNewResetTaskStatusCommand); + private async Task OnNewResetTaskStatusCommand() { - foreach (IGenericTaskModel chipTask in taskHandler.TaskCollection) + await Task.Run(() => { - chipTask.IsTaskCompletedSuccessfully = null; - chipTask.CurrentTaskErrorLevel = ERROR.Empty; - } + foreach (IGenericTaskModel chipTask in taskHandler.TaskCollection) + { + chipTask.IsTaskCompletedSuccessfully = null; + chipTask.CurrentTaskErrorLevel = ERROR.Empty; + } + }); } /// /// Reset all Reporttasks directory information /// - public ICommand ResetReportTaskDirectoryCommand => new RelayCommand(OnNewResetReportTaskDirectoryCommand); - private void OnNewResetReportTaskDirectoryCommand() + public IAsyncRelayCommand ResetReportTaskDirectoryCommand => new AsyncRelayCommand(OnNewResetReportTaskDirectoryCommand); + private async Task OnNewResetReportTaskDirectoryCommand() { - try + await Task.Run(async () => { - foreach (var chipTask in taskHandler.TaskCollection) + try { - switch (chipTask) + foreach (var chipTask in taskHandler.TaskCollection) { - case CommonTaskViewModel ssVM: - ssVM.IsTaskCompletedSuccessfully = null; - reportOutputPath = null; - reportReaderWriter.ReportOutputPath = null; - reportReaderWriter.ReportTemplateFile = null; - ssVM.CurrentTaskErrorLevel = ERROR.Empty; - break; + switch (chipTask) + { + case CommonTaskViewModel ssVM: + ssVM.IsTaskCompletedSuccessfully = null; + reportOutputPath = null; + reportReaderWriter.ReportOutputPath = null; + reportReaderWriter.ReportTemplateFile = null; + ssVM.CurrentTaskErrorLevel = ERROR.Empty; + break; + } } } - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + } + }); + } /// /// Reset selected Task status information /// - public ICommand ResetSelectedTaskStatusCommand => new RelayCommand(OnNewResetSelectedTaskStatusCommand); - private void OnNewResetSelectedTaskStatusCommand() + public IAsyncRelayCommand ResetSelectedTaskStatusCommand => new AsyncRelayCommand(OnNewResetSelectedTaskStatusCommand); + private async Task OnNewResetSelectedTaskStatusCommand() { - (SelectedSetupViewModel as IGenericTaskModel).IsTaskCompletedSuccessfully = null; - (SelectedSetupViewModel as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.Empty; + await Task.Run(() => + { + (SelectedSetupViewModel as IGenericTaskModel).IsTaskCompletedSuccessfully = null; + (SelectedSetupViewModel as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.Empty; + }); } /// /// Remove all Tasks from DataGrid /// - public ICommand RemoveAllTasksCommand => new RelayCommand(OnNewRemoveAllTasksCommand); - private void OnNewRemoveAllTasksCommand() + public IAsyncRelayCommand RemoveAllTasksCommand => new AsyncRelayCommand(OnNewRemoveAllTasksCommand); + private async Task OnNewRemoveAllTasksCommand() { - taskHandler.TaskCollection.Clear(); + await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => taskHandler.TaskCollection.Clear())); } /// @@ -1097,26 +1140,31 @@ private void OnNewWriteToAllChipAutoCommand() /// /// /// - public ICommand WriteSelectedTaskToChipOnceCommand => new RelayCommand(OnNewWriteSelectedTaskToChipOnceCommand); - private void OnNewWriteSelectedTaskToChipOnceCommand() + public IAsyncRelayCommand WriteSelectedTaskToChipOnceCommand => new AsyncRelayCommand(OnNewWriteSelectedTaskToChipOnceCommand); + private async Task OnNewWriteSelectedTaskToChipOnceCommand() { _runSelectedOnly = true; - OnNewWriteToChipOnceCommand(); + await WriteToChipOnceCommand.ExecuteAsync(null); } /// /// /// - public ICommand WriteToChipOnceCommand => new RelayCommand(OnNewWriteToChipOnceCommand); - private void OnNewWriteToChipOnceCommand() + public IAsyncRelayCommand WriteToChipOnceCommand => new AsyncRelayCommand(OnNewWriteToChipOnceCommand); + private async Task OnNewWriteToChipOnceCommand() { - OnNewReadChipCommand(); + Mouse.OverrideCursor = Cursors.AppStarting; + + if (!_runSelectedOnly) + { + await OnNewResetTaskStatusCommand(); + } + + await OnNewReadChipCommand(); OnPropertyChanged(nameof(TreeViewParentNodes)); OnPropertyChanged(nameof(ChipTasks)); - var GenericChip = new GenericChipModel("", CARD_TYPE.Unspecified); - var DesfireChip = new MifareDesfireChipModel("", CARD_TYPE.Unspecified); - var ClassicChip = new MifareClassicChipModel("", CARD_TYPE.Unspecified); + var GenericChip = new GenericChipModel("", CARD_TYPE.NOTAG); currentTaskIndex = 0; var taskDictionary = new Dictionary(); @@ -1138,487 +1186,487 @@ private void OnNewWriteToChipOnceCommand() triggerReadChip.Tag = triggerReadChip.IsEnabled; triggerReadChip.IsEnabled = false; - var thread = new Task(() => + try { - try + //try to get singleton instance + using (var device = ReaderDevice.Instance) { - //try to get singleton instance - using (var device = ReaderDevice.Instance) + //reader was ready - proceed + if (device != null) { - //reader was ready - proceed - if (device != null) + await device.ReadChipPublic(); + + if (device.GenericChip != null && device.GenericChip.Count > 0) { - device.ReadChipPublic(); + GenericChip = device.GenericChip[0]; - if (device.GenericChip != null) + if (GenericChip.CardType.ToString().ToLower(CultureInfo.CurrentCulture).Contains("desfire")) { - //GenericChip.CardType = device.GenericChip.CardType; - //GenericChip.UID = device.GenericChip.UID; - GenericChip = device.GenericChip; - - if (GenericChip.CardType.ToString().ToLower(CultureInfo.CurrentCulture).Contains("desfire")) - { - device.GetMiFareDESFireChipAppIDs(); - } + await device.GetMiFareDESFireChipAppIDs(); } } + } - if (treeViewParentNodes.Any(x => x.IsSelected)) - { - treeViewParentNodes.First(x => x.IsSelected).IsSelected = false; - } + if (treeViewParentNodes.Any(x => x.IsSelected)) + { + treeViewParentNodes.First(x => x.IsSelected).IsSelected = false; + } + + //only run if theres a hfTag on the reader and its uid was previously added + if ( + !string.IsNullOrWhiteSpace(GenericChip.UID) && + treeViewParentNodes.Any(x => x.UID == GenericChip.UID)) + { + //select current parentnode (hfTag) on reader + treeViewParentNodes.First(x => x.UID == GenericChip.UID).IsSelected = true; + treeViewParentNodes.First(x => x.IsSelected).IsBeingProgrammed = true; + } + + //are there tasks present to process? + while (currentTaskIndex < taskHandler.TaskCollection.Count) + { + await Task.Delay(50); - //only run if theres a hfTag on the reader and its uid was previously added - if ( - !string.IsNullOrWhiteSpace(GenericChip.UID) && - treeViewParentNodes.Any(x => x.UID == GenericChip.UID)) + if (_runSelectedOnly) { - //select current parentnode (hfTag) on reader - treeViewParentNodes.First(x => x.UID == GenericChip.UID).IsSelected = true; - treeViewParentNodes.First(x => x.IsSelected).IsBeingProgrammed = true; + currentTaskIndex = taskHandler.TaskCollection.IndexOf(SelectedSetupViewModel); } - //are there tasks present to process? - while (currentTaskIndex < taskHandler.TaskCollection.Count) - { - if (_runSelectedOnly) - { - currentTaskIndex = taskHandler.TaskCollection.IndexOf(SelectedSetupViewModel); - } + taskTimeout.Stop(); + taskTimeout.Start(); + taskTimeout.IsEnabled = true; + taskTimeout.Tag = currentTaskIndex; - Thread.Sleep(20); + SelectedSetupViewModel = taskHandler.TaskCollection[currentTaskIndex]; - taskTimeout.Stop(); - taskTimeout.Start(); - taskTimeout.IsEnabled = true; - taskTimeout.Tag = currentTaskIndex; + //decide what type of task to process next. use exact array positions + switch (taskHandler.TaskCollection[currentTaskIndex]) + { - SelectedSetupViewModel = taskHandler.TaskCollection[currentTaskIndex]; + case CommonTaskViewModel csVM: - //decide what type of task to process next. use exact array positions - switch (taskHandler.TaskCollection[currentTaskIndex]) - { + (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).GenericChip = GenericChip; + (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).DesfireChip = device.DesfireChip; + (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).AvailableTasks = taskHandler.TaskCollection; + (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).Args = variablesFromArgs; - case CommonTaskViewModel csVM: + switch (csVM.SelectedTaskType) + { + case TaskType_CommonTask.CreateReport: + taskTimeout.Stop(); + switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) + { + case ERROR.NotReadyError: + break; - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).GenericChip = GenericChip; - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).DesfireChip = device.DesfireChip; - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).AvailableTasks = taskHandler.TaskCollection; - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).Args = variablesFromArgs; + case ERROR.Empty: + (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CurrentTaskErrorLevel = ERROR.NotReadyError; + taskTimeout.Start(); + taskTimeout.Stop(); - switch (csVM.SelectedTaskType) - { - case TaskType_CommonTask.CreateReport: - taskTimeout.Stop(); - switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) - { - case ERROR.NotReadyError: - break; + DirectoryInfo reportTargetPathDirInfo; - case ERROR.Empty: - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CurrentTaskErrorLevel = ERROR.NotReadyError; - taskTimeout.Start(); - taskTimeout.Stop(); + try + { + var targetReportDir = variablesFromArgs["REPORTTARGETPATH"]; + var sourceTemplateFile = variablesFromArgs["REPORTTEMPLATEFILE"]; + reportTargetPathDirInfo = new DirectoryInfo(Path.GetDirectoryName(targetReportDir)); - DirectoryInfo reportTargetPathDirInfo; - - try - { - var targetReportDir = variablesFromArgs["REPORTTARGETPATH"]; - var sourceTemplateFile = variablesFromArgs["REPORTTEMPLATEFILE"]; - reportTargetPathDirInfo = new DirectoryInfo(Path.GetDirectoryName(targetReportDir)); - - } - catch - { - reportTargetPathDirInfo = null; - } + } + catch + { + reportTargetPathDirInfo = null; + } - if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) + if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) + { + if (string.IsNullOrEmpty(reportOutputPath)) { - if (string.IsNullOrEmpty(reportOutputPath)) + var dlg = new SaveFileDialogViewModel { - var dlg = new SaveFileDialogViewModel - { - Title = ResourceLoader.GetResource("windowCaptionSaveReport"), - Filter = ResourceLoader.GetResource("filterStringSaveReport"), - ParentWindow = this.mw, - InitialDirectory = reportTargetPathDirInfo != null ? - (reportTargetPathDirInfo.Exists ? reportTargetPathDirInfo.FullName : null) : null - }; - - if (dlg.Show(Dialogs) && dlg.FileName != null) - { - reportOutputPath = dlg.FileName; - } - } - - if (reportReaderWriter == null) + Title = ResourceLoader.GetResource("windowCaptionSaveReport"), + Filter = ResourceLoader.GetResource("filterStringSaveReport"), + ParentWindow = this.mw, + InitialDirectory = reportTargetPathDirInfo != null ? + (reportTargetPathDirInfo.Exists ? reportTargetPathDirInfo.FullName : null) : null + }; + + if (dlg.Show(Dialogs) && dlg.FileName != null) { - reportReaderWriter = new ReportReaderWriter(); + reportOutputPath = dlg.FileName; } + } - reportReaderWriter.ReportOutputPath = reportOutputPath; - if (!string.IsNullOrEmpty(reportTemplateFile)) - { - reportReaderWriter.ReportTemplateFile = reportTemplateFile; - } + if (reportReaderWriter == null) + { + reportReaderWriter = new ReportReaderWriter(); + } - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).WriteReportCommand.Execute(reportReaderWriter); + reportReaderWriter.ReportOutputPath = reportOutputPath; + if (!string.IsNullOrEmpty(reportTemplateFile)) + { + reportReaderWriter.ReportTemplateFile = reportTemplateFile; } - else + await (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).WriteReportCommand.ExecuteAsync(reportReaderWriter); + } + + else + { + // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL + if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) { - // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL - if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) + if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) { - if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) + if (string.IsNullOrEmpty(reportOutputPath)) { - if (string.IsNullOrEmpty(reportOutputPath)) - { - - var dlg = new SaveFileDialogViewModel - { - Title = ResourceLoader.GetResource("windowCaptionSaveReport"), - Filter = ResourceLoader.GetResource("filterStringSaveReport"), - InitialDirectory = reportTargetPathDirInfo != null ? - (reportTargetPathDirInfo.Exists ? reportTargetPathDirInfo.FullName : null) : null - }; - - if (dlg.Show(Dialogs) && dlg.FileName != null) - { - reportOutputPath = dlg.FileName; - } - } - if (reportReaderWriter == null) + var dlg = new SaveFileDialogViewModel { - reportReaderWriter = new ReportReaderWriter(); - } + Title = ResourceLoader.GetResource("windowCaptionSaveReport"), + Filter = ResourceLoader.GetResource("filterStringSaveReport"), + InitialDirectory = reportTargetPathDirInfo != null ? + (reportTargetPathDirInfo.Exists ? reportTargetPathDirInfo.FullName : null) : null + }; - reportReaderWriter.ReportOutputPath = reportOutputPath; - if (!string.IsNullOrEmpty(reportTemplateFile)) + if (dlg.Show(Dialogs) && dlg.FileName != null) { - reportReaderWriter.ReportTemplateFile = reportTemplateFile; + reportOutputPath = dlg.FileName; } + } - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).WriteReportCommand.Execute(reportReaderWriter); + if (reportReaderWriter == null) + { + reportReaderWriter = new ReportReaderWriter(); } - else + + reportReaderWriter.ReportOutputPath = reportOutputPath; + if (!string.IsNullOrEmpty(reportTemplateFile)) { - currentTaskIndex++; + reportReaderWriter.ReportTemplateFile = reportTemplateFile; } + + await (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).WriteReportCommand.ExecuteAsync(reportReaderWriter); + } + else + { + currentTaskIndex++; } } + } - taskTimeout.Start(); - break; + taskTimeout.Start(); + break; - default: - currentTaskIndex++; - taskTimeout.Stop(); - taskTimeout.Start(); - break; - } - break; + default: + currentTaskIndex++; + taskTimeout.Stop(); + taskTimeout.Start(); + break; + } + break; - case TaskType_CommonTask.CheckLogicCondition: - switch ((taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CurrentTaskErrorLevel) - { - case ERROR.NotReadyError: - taskTimeout.Start(); - break; + case TaskType_CommonTask.CheckLogicCondition: + switch ((taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CurrentTaskErrorLevel) + { + case ERROR.NotReadyError: + taskTimeout.Start(); + break; - case ERROR.Empty: - (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.NotReadyError; - taskTimeout.Start(); + case ERROR.Empty: + (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.NotReadyError; + taskTimeout.Start(); - if ((taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) - { - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CheckLogicCondition.Execute(taskHandler.TaskCollection); - } + if ((taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) + { - else + await (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CheckLogicCondition.ExecuteAsync(taskHandler.TaskCollection); + } + + else + { + // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL + if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) { - // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL - if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) + if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) { - if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) - { - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CheckLogicCondition.Execute(taskHandler.TaskCollection); - } - else - { - currentTaskIndex++; - } + + await (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CheckLogicCondition.ExecuteAsync(taskHandler.TaskCollection); + } + else + { + currentTaskIndex++; } } - break; + } + break; - default: - currentTaskIndex++; - taskTimeout.Stop(); - taskTimeout.Start(); - break; - } - break; + default: + currentTaskIndex++; + taskTimeout.Stop(); + taskTimeout.Start(); + break; + } + break; - case TaskType_CommonTask.ExecuteProgram: - switch ((taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CurrentTaskErrorLevel) - { - case ERROR.NotReadyError: - taskTimeout.Start(); - break; + case TaskType_CommonTask.ExecuteProgram: + switch ((taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).CurrentTaskErrorLevel) + { + case ERROR.NotReadyError: + taskTimeout.Start(); + break; - case ERROR.Empty: - (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.NotReadyError; - taskTimeout.Start(); + case ERROR.Empty: + (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.NotReadyError; + taskTimeout.Start(); - if ((taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) - { - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).ExecuteProgramCommand.Execute(null); - } + if ((taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) + { + (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).ExecuteProgramCommand.Execute(null); + } - else + else + { + // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL + if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) { - // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL - if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) + if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) { - if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) - { - (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).ExecuteProgramCommand.Execute(null); - } - else - { - currentTaskIndex++; - } + (taskHandler.TaskCollection[currentTaskIndex] as CommonTaskViewModel).ExecuteProgramCommand.Execute(null); + } + else + { + currentTaskIndex++; } } - break; + } + break; - default: - currentTaskIndex++; - taskTimeout.Stop(); - taskTimeout.Start(); - break; - } - break; + default: + currentTaskIndex++; + taskTimeout.Stop(); + taskTimeout.Start(); + break; + } + break; - default: - break; - } - break; + default: + break; + } + break; - case GenericChipTaskViewModel csVM: - switch (csVM.SelectedTaskType) - { - case TaskType_GenericChipTask.ChipIsOfType: - taskTimeout.Start(); - switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) - { - case ERROR.Empty: - (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).IsFocused = true; + case GenericChipTaskViewModel csVM: + switch (csVM.SelectedTaskType) + { + case TaskType_GenericChipTask.ChipIsOfType: + taskTimeout.Start(); + switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) + { + case ERROR.Empty: + (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).IsFocused = true; - if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) - { - (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).CheckChipType.Execute(null); - } - else + if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) + { + IsReaderBusy = true; + await (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).CheckChipType.ExecuteAsync(device.GenericChip); + } + else + { + // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL + if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) { - // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL - if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) + if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) { - if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) - { - (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).CheckChipType.Execute(null); - } - else - { - currentTaskIndex++; - } + IsReaderBusy = true; + await (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).CheckChipType.ExecuteAsync(device.GenericChip); + } + else + { + currentTaskIndex++; } } - break; + } - default: - (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).IsFocused = false; - currentTaskIndex++; - break; - } - break; + IsReaderBusy = false; + break; - case TaskType_GenericChipTask.ChipIsMultiChip: - taskTimeout.Start(); - switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) - { - case ERROR.Empty: - (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).IsFocused = true; + default: + (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).IsFocused = false; + currentTaskIndex++; + break; + } + break; - if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) - { - (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).CheckChipIsMultiTecChip.Execute(null); - } - else + case TaskType_GenericChipTask.ChipIsMultiChip: + taskTimeout.Start(); + switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) + { + case ERROR.Empty: + (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).IsFocused = true; + + if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) + { + IsReaderBusy = true; + await (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).CheckChipIsMultiTecChip.ExecuteAsync(device.GenericChip); + } + else + { + // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL + if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) { - // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL - if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) + if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) { - if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) - { - (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).CheckChipIsMultiTecChip.Execute(null); - } - else - { - currentTaskIndex++; - } + IsReaderBusy = true; + await (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).CheckChipIsMultiTecChip.ExecuteAsync(device.GenericChip); + } + else + { + currentTaskIndex++; } } - break; + } - default: - (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).IsFocused = false; - currentTaskIndex++; - break; - } - break; - default: - break; - } - break; + IsReaderBusy = false; + break; - case MifareClassicSetupViewModel csVM: - switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) - { - case ERROR.NotReadyError: - taskTimeout.Start(); - break; + default: + (taskHandler.TaskCollection[currentTaskIndex] as GenericChipTaskViewModel).IsFocused = false; + currentTaskIndex++; + break; + } + break; + default: + break; + } + break; - case ERROR.Empty: - (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.NotReadyError; - taskTimeout.Start(); + case MifareClassicSetupViewModel csVM: + switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) + { + case ERROR.NotReadyError: + taskTimeout.Start(); + break; - if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) - { - (taskHandler.TaskCollection[currentTaskIndex] as MifareClassicSetupViewModel).CommandDelegator.Execute(csVM.SelectedTaskType); - } + case ERROR.Empty: + (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.NotReadyError; + taskTimeout.Start(); + + if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) + { + IsReaderBusy = true; + await (taskHandler.TaskCollection[currentTaskIndex] as MifareClassicSetupViewModel).CommandDelegator.ExecuteAsync(csVM.SelectedTaskType); + } - else + else + { + // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL + if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) { - // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL - if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) + if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) { - if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) - { - (taskHandler.TaskCollection[currentTaskIndex] as MifareClassicSetupViewModel).CommandDelegator.Execute(csVM.SelectedTaskType); - } - else - { - currentTaskIndex++; - } + IsReaderBusy = true; + await (taskHandler.TaskCollection[currentTaskIndex] as MifareClassicSetupViewModel).CommandDelegator.ExecuteAsync(csVM.SelectedTaskType); + } + else + { + currentTaskIndex++; } } + } - break; + IsReaderBusy = false; + break; - default: - currentTaskIndex++; - taskTimeout.Stop(); - taskTimeout.Start(); - break; - } - break; + default: + currentTaskIndex++; + taskTimeout.Stop(); + taskTimeout.Start(); + break; + } + break; - case MifareDesfireSetupViewModel csVM: - switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) - { - case ERROR.NotReadyError: - taskTimeout.Start(); - break; + case MifareDesfireSetupViewModel csVM: + switch ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel) + { + case ERROR.NotReadyError: + taskTimeout.Start(); + break; - case ERROR.Empty: - (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.NotReadyError; - taskTimeout.Start(); + case ERROR.Empty: + (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel = ERROR.NotReadyError; + taskTimeout.Start(); - if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) - { - (taskHandler.TaskCollection[currentTaskIndex] as MifareDesfireSetupViewModel).CommandDelegator.Execute(csVM.SelectedTaskType); - } + if ((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel == ERROR.Empty) + { + IsReaderBusy = true; + await (taskHandler.TaskCollection[currentTaskIndex] as MifareDesfireSetupViewModel).CommandDelegator.ExecuteAsync(csVM.SelectedTaskType); + } - else + else + { + // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL + if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) { - // targeted ERRORLEVEL ist not "EMPTY" so check if targeted ERRORLEVEL fits current ERRORLEVEL - if (taskDictionary.TryGetValue((taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionTaskIndex, out var targetTaskIndex)) + if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) { - if ((taskHandler.TaskCollection[targetTaskIndex] as IGenericTaskModel).CurrentTaskErrorLevel == (taskHandler.TaskCollection[currentTaskIndex] as IGenericTaskModel).SelectedExecuteConditionErrorLevel) - { - (taskHandler.TaskCollection[currentTaskIndex] as MifareDesfireSetupViewModel).CommandDelegator.Execute(csVM.SelectedTaskType); - } - else - { - currentTaskIndex++; - } + IsReaderBusy = true; + await (taskHandler.TaskCollection[currentTaskIndex] as MifareDesfireSetupViewModel).CommandDelegator.ExecuteAsync(csVM.SelectedTaskType); + } + else + { + currentTaskIndex++; } } + } - break; - - default: - currentTaskIndex++; - taskTimeout.Stop(); - taskTimeout.Start(); - break; - - } - break; - - case MifareUltralightSetupViewModel ssVM: - break; + IsReaderBusy = false; + break; - default: - break; - } + default: + currentTaskIndex++; + taskTimeout.Stop(); + taskTimeout.Start(); + break; + } + break; - if (_runSelectedOnly) - { + case MifareUltralightSetupViewModel ssVM: break; - } - OnPropertyChanged(nameof(TreeViewParentNodes)); + default: + break; } - } - OnPropertyChanged(nameof(TreeViewParentNodes)); - taskTimeout.Stop(); + if (_runSelectedOnly) + { + break; + } + OnPropertyChanged(nameof(TreeViewParentNodes)); + } } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } - }); + OnPropertyChanged(nameof(TreeViewParentNodes)); + taskTimeout.Stop(); - thread.ContinueWith((x) => + } + catch (Exception e) { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + } - try - { - treeViewParentNodes.First(y => y.IsSelected).IsBeingProgrammed = null; - triggerReadChip.IsEnabled = (bool)triggerReadChip.Tag; - _runSelectedOnly = false; - } - - catch { } - }); - - if(!_runSelectedOnly) + try { - OnNewResetTaskStatusCommand(); + treeViewParentNodes.First(y => y.IsSelected).IsBeingProgrammed = null; + triggerReadChip.IsEnabled = (bool)triggerReadChip.Tag; + _runSelectedOnly = false; } - thread.Start(); + catch { } + + } /// @@ -1633,15 +1681,15 @@ private void OnCloseAll() /// /// /// - public ICommand SwitchLanguageToGerman => new RelayCommand(SetGermanLanguage); - private void SetGermanLanguage() + public IAsyncRelayCommand SwitchLanguageToGerman => new AsyncRelayCommand(SetGermanLanguage); + private async Task SetGermanLanguage() { using (var settings = new SettingsReaderWriter()) { if (settings.DefaultSpecification.DefaultLanguage != "german") { settings.DefaultSpecification.DefaultLanguage = "german"; - settings.SaveSettings(); + await settings.SaveSettings(); OnNewLanguageChangedDialog(); } } @@ -1650,15 +1698,15 @@ private void SetGermanLanguage() /// /// /// - public ICommand SwitchLanguageToEnglish => new RelayCommand(SetEnglishLanguage); - private void SetEnglishLanguage() + public IAsyncRelayCommand SwitchLanguageToEnglish => new AsyncRelayCommand(SetEnglishLanguage); + private async Task SetEnglishLanguage() { using (var settings = new SettingsReaderWriter()) { if (settings.DefaultSpecification.DefaultLanguage != "english") { settings.DefaultSpecification.DefaultLanguage = "english"; - settings.SaveSettings(); + await settings.SaveSettings(); OnNewLanguageChangedDialog(); } } @@ -1670,7 +1718,7 @@ private void SetEnglishLanguage() private void OnNewLanguageChangedDialog() { Dialogs.Add(new CustomDialogViewModel() - { + { Message = ResourceLoader.GetResource("messageBoxRestartRequiredMessage"), Caption = ResourceLoader.GetResource("messageBoxRestartRequiredCaption"), @@ -1692,8 +1740,31 @@ private void OnNewLanguageChangedDialog() /// /// /// - public ICommand NewReaderSetupDialogCommand => new RelayCommand(OnNewReaderSetupDialog); - private void OnNewReaderSetupDialog() + private void OnNewNoReaderFoundDialog() + { + Dialogs.Add(new CustomDialogViewModel() + { + Message = ResourceLoader.GetResource("messageBoxNoReaderFoundMessage"), + Caption = ResourceLoader.GetResource("messageBoxNoReaderFoundCaption"), + + OnCancel = (sender) => + { + sender.Close(); + }, + + OnOk = (sender) => + { + sender.Close(); + } + }); + + } + + /// + /// + /// + public IAsyncRelayCommand NewReaderSetupDialogCommand => new AsyncRelayCommand(OnNewReaderSetupDialog); + private async Task OnNewReaderSetupDialog() { using (var settings = new SettingsReaderWriter()) { @@ -1718,29 +1789,46 @@ private void OnNewReaderSetupDialog() settings.DefaultSpecification = currentSettings; - sender.Close(); - - settings.SaveSettings(); + sender.SaveSettings.ExecuteAsync(null); CurrentReader = Enum.GetName(typeof(ReaderTypes), sender.SelectedReader); ReaderDevice.Reader = (ReaderTypes)Enum.Parse(typeof(ReaderTypes), CurrentReader); - }, + sender.Close(); + IsReaderBusy = false; + }, + OnConnect = (sender) => { + IsReaderBusy = true; + }, + + OnUpdateReaderStatus = (sender) => + { + IsReaderBusy = sender; + }, + + OnBeginUpdateCheck = (sender) => + { + if (sender) + { + updater?.StartMonitoring(); + } }, OnCancel = (sender) => { sender.Close(); + IsReaderBusy = false; mw.Activate(); }, OnCloseRequest = (sender) => { sender.Close(); + IsReaderBusy = false; mw.Activate(); } }); @@ -1748,11 +1836,13 @@ private void OnNewReaderSetupDialog() } } + private void MainWindowViewModel_ReaderStatusChanged(object sender, EventArgs e) => throw new NotImplementedException(); + /// /// /// - public ICommand NewOpenFileDialogCommand => new RelayCommand(OnNewOpenFileDialog); - private void OnNewOpenFileDialog() + public IAsyncRelayCommand NewOpenFileDialogCommand => new AsyncRelayCommand(OnNewOpenFileDialog); + private async Task OnNewOpenFileDialog() { bool autoLoadLastUsedDB; string lastUsedDBPath; @@ -1786,10 +1876,10 @@ private void OnNewOpenFileDialog() ChipTasks.TaskCollection.Clear(); } - databaseReaderWriter.ReadDatabase(dlg.FileName); + await databaseReaderWriter.ReadDatabase(dlg.FileName).ConfigureAwait(false); settings.DefaultSpecification.LastUsedProjectPath = dlg.FileName; - settings.SaveSettings(); + await settings.SaveSettings(); foreach (var vm in databaseReaderWriter.TreeViewModel) { @@ -1798,13 +1888,15 @@ private void OnNewOpenFileDialog() foreach (var setup in databaseReaderWriter.SetupModel.TaskCollection) { - ChipTasks.TaskCollection.Add(setup); + await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => ChipTasks.TaskCollection.Add(setup))); } } - - } - Mouse.OverrideCursor = null; + + await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => + { + Mouse.OverrideCursor = null; + })); OnPropertyChanged(nameof(ChipTasks)); } @@ -1812,22 +1904,22 @@ private void OnNewOpenFileDialog() /// /// Expose Command to Save ProjectFile Menu Item /// - public ICommand SaveTaskDialogCommand => new RelayCommand(OnNewSaveTaskDialogCommand); - private void OnNewSaveTaskDialogCommand() + public IAsyncRelayCommand SaveTaskDialogCommand => new AsyncRelayCommand(OnNewSaveTaskDialogCommand); + private async Task OnNewSaveTaskDialogCommand() { using (var settings = new SettingsReaderWriter()) { databaseReaderWriter.WriteDatabase(ChipTasks, settings.DefaultSpecification.LastUsedProjectPath); - } - } + } + } /// /// Expose Command to Save As Menu Item /// - public ICommand SaveTaskAsDialogCommand => new RelayCommand(OnNewSaveTaskAsDialogCommand); - private void OnNewSaveTaskAsDialogCommand() + public IAsyncRelayCommand SaveTaskAsDialogCommand => new AsyncRelayCommand(OnNewSaveTaskAsDialogCommand); + private async Task OnNewSaveTaskAsDialogCommand() { - var fileName = ""; + string fileName; var dlg = new SaveFileDialogViewModel { @@ -1846,6 +1938,7 @@ private void OnNewSaveTaskAsDialogCommand() var mbox = new MessageBoxViewModel { + ParentWindow = mw, Caption = ResourceLoader.GetResource("windowCaptionAskTaskDefault"), Message = ResourceLoader.GetResource("messageBoxMessageSetProjectAsDefault"), Buttons = MessageBoxButton.YesNo @@ -1856,7 +1949,7 @@ private void OnNewSaveTaskAsDialogCommand() using (var settings = new SettingsReaderWriter()) { settings.DefaultSpecification.LastUsedProjectPath = fileName; - settings.SaveSettings(); + await settings.SaveSettings(); } } @@ -1869,8 +1962,8 @@ private void OnNewSaveTaskAsDialogCommand() /// /// Expose Command to Save Menu Item /// - public ICommand SaveChipDialogCommand => new RelayCommand(OnNewSaveChipDialogCommand); - private void OnNewSaveChipDialogCommand() + public IAsyncRelayCommand SaveChipDialogCommand => new AsyncRelayCommand(OnNewSaveChipDialogCommand); + private async Task OnNewSaveChipDialogCommand() { var dlg = new SaveFileDialogViewModel { @@ -1910,12 +2003,25 @@ private void OnNewShowHelpCommand() /// /// /// - public ICommand CheckUpdateCommand => new RelayCommand(OnNewCheckUpdateCommand); - private void OnNewCheckUpdateCommand() + public IAsyncRelayCommand CheckUpdateCommand => new AsyncRelayCommand(OnNewCheckUpdateCommand); + private async void CheckUpdate(object sender) + { + checkUpdate.Change(Timeout.Infinite, Timeout.Infinite); + + if (updater.UpdateAvailable) + { + await AskForUpdateNow(); + } + + checkUpdate.Change(5000, 5000); + } + private async Task OnNewCheckUpdateCommand() { - if (updateIsAvailable) + userIsNotifiedForAvailableUpdate = false; + + if (updater.UpdateAvailable) { - AskForUpdateNow(); + await AskForUpdateNow(); } } @@ -2051,7 +2157,38 @@ public string DateTimeStatusBar /// /// /// - public bool IsSelected { get; set; } + public bool IsSelected + { + get; set; + } + + /// + /// + /// + public bool? IsReaderBusy + { + get => isReaderBusy; + set + { + isReaderBusy = value; + if (value == true) + { + if (checkReader != null) + { + checkReader.Change(Timeout.Infinite, Timeout.Infinite); + } + } + else + { + if (checkReader != null) + { + checkReader.Change(2000, 2000); + } + } + OnPropertyChanged(nameof(IsReaderBusy)); + } + } + private bool? isReaderBusy; /// /// @@ -2071,15 +2208,15 @@ public bool IsCheckForUpdatesChecked { if (value) { - updater.StartMonitoring(); + updater.StartMonitoring().GetAwaiter().GetResult(); } else { - updater.StopMonitoring(); + updater.StopMonitoring().GetAwaiter().GetResult(); } settings.DefaultSpecification.AutoCheckForUpdates = value; - settings.SaveSettings(); + settings.SaveSettings().GetAwaiter().GetResult(); } OnPropertyChanged(nameof(IsCheckForUpdatesChecked)); @@ -2158,47 +2295,60 @@ public bool RadioButtonEnglishLanguageSelectedState private void EnableUpdate(object sender, EventArgs e) { userIsNotifiedForAvailableUpdate = true; - updateIsAvailable = true; } - private void AskForUpdateNow() + /// + /// + /// + /// + private async Task AskForUpdateNow() { - AskForUpdateNow(false); + await AskForUpdateNow(false); } - private void AskForUpdateNow(bool updateDisabled) + /// + /// + /// + /// + /// + private async Task AskForUpdateNow(bool updateDisabled) { - userIsNotifiedForAvailableUpdate = false; - - Dialogs.Add(new UpdateNotifierViewModel(updater.UpdateInfoText) + if (!userIsNotifiedForAvailableUpdate || updateDisabled) { - - Caption = updateDisabled ? "Changelog" : "Update Available", - - OnOk = (updateAction) => + await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { - if (!updateDisabled) + Dialogs.Add(new UpdateNotifierViewModel(updater.UpdateInfoText) { - Mouse.OverrideCursor = Cursors.AppStarting; - updater.Update(); - } - updateAction.Close(); - }, + Caption = updateDisabled ? "Changelog" : "Update Available", - OnCancel = (updateAction) => - { - updater.AllowUpdate = false; - updateAction.Close(); - mw.Activate(); - }, + OnOk = async (updateAction) => + { + if (!updateDisabled) + { + Mouse.OverrideCursor = Cursors.AppStarting; + await updater.Update(); + } + updateAction.Close(); + }, - OnCloseRequest = (updateAction) => - { - updater.AllowUpdate = false; - updateAction.Close(); - mw.Activate(); - } - }); + OnCancel = (updateAction) => + { + updater.AllowUpdate = false; + updateAction.Close(); + mw.Activate(); + }, + + OnCloseRequest = (updateAction) => + { + updater.AllowUpdate = false; + updateAction.Close(); + mw.Activate(); + } + }); + })); + } + + userIsNotifiedForAvailableUpdate = true; } //Only one instance is allowed due to the singleton pattern of the reader class @@ -2217,15 +2367,23 @@ private void CloseThreads(object sender, CancelEventArgs e) Environment.Exit(0); } - private void LoadCompleted(object sender, EventArgs e) + private async void LoadCompleted(object sender, EventArgs e) { + Application.Current.MainWindow.Activated -= new EventHandler(LoadCompleted); + mw = (MainWindow)Application.Current.MainWindow; mw.Title = string.Format("RFiDGear {0}.{1}", Version.Major, Version.Minor); - if (firstRun) - { - Task refreshStatusBarThread; + checkUpdate = new Timer(CheckUpdate, null, 100, 5000); // ! UI-Thread ! + checkReader = new Timer(CheckReader, null, 5000, 3000); // ! UI-Thread ! + + await Run(); + } + private async Task Run() + { + if (firstRun) + { var projectFileToUse = ""; firstRun = false; @@ -2234,6 +2392,10 @@ private void LoadCompleted(object sender, EventArgs e) { using (var settings = new SettingsReaderWriter()) { + await settings.ReadSettings(); + + settings.InitUpdateFile(); + if (args.Length > 1) { foreach (var arg in args) @@ -2245,7 +2407,7 @@ private void LoadCompleted(object sender, EventArgs e) if (File.Exists(arg.Split('=')[1])) { settings.DefaultSpecification.LastUsedProjectPath = new DirectoryInfo(arg.Split('=')[1]).FullName; - settings.SaveSettings(); + await settings.SaveSettings(); } break; @@ -2258,7 +2420,7 @@ private void LoadCompleted(object sender, EventArgs e) break; default: - break; + break; } } } @@ -2277,7 +2439,6 @@ private void LoadCompleted(object sender, EventArgs e) ReaderDevice.PortNumber = 0; } - culture = (settings.DefaultSpecification.DefaultLanguage == "german") ? new CultureInfo("de-DE") : new CultureInfo("en-US"); var autoLoadLastUsedDB = settings.DefaultSpecification.AutoLoadProjectOnStart; @@ -2293,31 +2454,26 @@ private void LoadCompleted(object sender, EventArgs e) { if (string.IsNullOrEmpty(projectFileToUse)) { - OpenLastProjectFile(); + await OpenLastProjectFile(); } else { - OpenLastProjectFile(projectFileToUse); + await OpenLastProjectFile(projectFileToUse); } - + } - refreshStatusBarThread = new Task(() => + + Task.Run(async () => { while (true) { - Thread.Sleep(500); + await Task.Delay(300); DateTimeStatusBar = string.Format("{0}", DateTime.Now); } }); - refreshStatusBarThread.ContinueWith((x) => - { - }); - - refreshStatusBarThread.Start(); - - OnNewResetTaskStatusCommand(); + await OnNewResetTaskStatusCommand(); } using (var settings = new SettingsReaderWriter()) @@ -2339,14 +2495,14 @@ private void LoadCompleted(object sender, EventArgs e) if (reportOutputPath.Contains("?")) { - for (int i = 0; i < numbersInFileNames.Length; i++) + for (var i = 0; i < numbersInFileNames.Length; i++) { var fileName = Directory.GetFiles(Path.GetDirectoryName(reportOutputPath))[i]; - if (fileName.Replace(".pdf",string.Empty).ToLower().Contains(reportOutputPath.ToLower().Replace("?",string.Empty).Replace(".pdf",string.Empty))) + if (fileName.Replace(".pdf", string.Empty).ToLower().Contains(reportOutputPath.ToLower().Replace("?", string.Empty).Replace(".pdf", string.Empty))) { _ = int.TryParse(fileName.ToLower().Replace( - reportOutputPath.ToLower().Replace("?", string.Empty).Replace(".pdf", string.Empty), string.Empty).Replace(".pdf", string.Empty), out int n); + reportOutputPath.ToLower().Replace("?", string.Empty).Replace(".pdf", string.Empty), string.Empty).Replace(".pdf", string.Empty), out var n); numbersInFileNames[i] = n; } } @@ -2367,7 +2523,7 @@ private void LoadCompleted(object sender, EventArgs e) reportOutputPath = reportOutputPath.Replace("?", string.Format("{0:D1}", numbersInFileNames.Max() + 1)); } } - break; + break; case "REPORTTEMPLATEFILE": @@ -2382,8 +2538,7 @@ private void LoadCompleted(object sender, EventArgs e) case "AUTORUN": if (arg.Split('=')[1] == "1") { - _isLoadingProject = true; - OnNewWriteToChipOnceCommand(); + await OnNewWriteToChipOnceCommand(); } break; @@ -2400,7 +2555,7 @@ private void LoadCompleted(object sender, EventArgs e) } catch (Exception ex) { - LogWriter.CreateLogEntry(ex, FacilityName); + eventLog.WriteEntry(ex.Message, EventLogEntryType.Error); } using (var settings = new SettingsReaderWriter()) @@ -2411,18 +2566,78 @@ private void LoadCompleted(object sender, EventArgs e) } } } + } + private async void CheckReader(object sender) + { + checkReader.Change(Timeout.Infinite, Timeout.Infinite); // ! UI-Thread ! - - - if (userIsNotifiedForAvailableUpdate) + using (var settings = new SettingsReaderWriter()) { - AskForUpdateNow(); - } + if (ReaderDevice.Instance != null && IsReaderBusy != true) + { + try + { + if (!ReaderDevice.Instance.IsConnected) + { + var result = await ReaderDevice.Instance.ConnectAsync(); + + if (result == ERROR.NoError) + { + IsReaderBusy = false; + CurrentReader = settings.DefaultSpecification.DefaultReaderProvider == ReaderTypes.None + ? "N/A" + : settings.DefaultSpecification.DefaultReaderProvider + " " + + ReaderDevice.Instance.ReaderUnitName + + ReaderDevice.Instance.ReaderUnitVersion; + } + else + { + IsReaderBusy = null; + CurrentReader = settings.DefaultSpecification.DefaultReaderProvider == ReaderTypes.None + ? "N/A" + : settings.DefaultSpecification.DefaultReaderProvider.ToString(); + } + } + else + { + CurrentReader = settings.DefaultSpecification.DefaultReaderProvider == ReaderTypes.None + ? "N/A" + : settings.DefaultSpecification.DefaultReaderProvider + " " + + ReaderDevice.Instance.ReaderUnitName + + ReaderDevice.Instance.ReaderUnitVersion; + } + } + catch + { + CurrentReader = settings.DefaultSpecification.DefaultReaderProvider == ReaderTypes.None + ? "N/A" + : settings.DefaultSpecification.DefaultReaderProvider.ToString(); + } + } + else if (ReaderDevice.Instance != null && IsReaderBusy != true) + { + IsReaderBusy = null; + CurrentReader = settings.DefaultSpecification.DefaultReaderProvider == ReaderTypes.None + ? "N/A" + : settings.DefaultSpecification.DefaultReaderProvider.ToString(); + await ReaderDevice.Instance.ConnectAsync().ConfigureAwait(false); + if (ReaderDevice.Instance.IsConnected) + { + IsReaderBusy = false; + } + } + }; + + checkReader.Change(2000, 2000); + + } + + private bool ContainsAny(string haystack, params string[] needles) + { + return needles.Any(haystack.Contains); } - private bool ContainsAny(string haystack, params string[] needles) { return needles.Any(haystack.Contains); } - #endregion } } \ No newline at end of file diff --git a/RFiDGear/ViewModel/SetupViewModel.cs b/RFiDGear/ViewModel/SetupViewModel.cs index 16bcec3..b7d5ee3 100644 --- a/RFiDGear/ViewModel/SetupViewModel.cs +++ b/RFiDGear/ViewModel/SetupViewModel.cs @@ -8,14 +8,17 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using RFiDGear.DataAccessLayer.Remote.FromIO; using RFiDGear.DataAccessLayer; using System; +using System.Threading.Tasks; using System.Collections.Generic; using System.Windows.Input; +using System.Data; +using System.Xml.Serialization; namespace RFiDGear.ViewModel { @@ -42,12 +45,19 @@ public SetupViewModel(ReaderDevice _device) LoadOnStart = settings.DefaultSpecification.AutoLoadProjectOnStart; CheckOnStart = settings.DefaultSpecification.AutoCheckForUpdates; SelectedBaudRate = settings.DefaultSpecification.LastUsedBaudRate; - - //ConnectToReaderCommand.Execute(null); } } #region Commands + /// + /// + /// + public IAsyncRelayCommand SaveSettings => new AsyncRelayCommand(OnNewSaveSettingsCommand); + private async Task OnNewSaveSettingsCommand() + { + SettingsReaderWriter settings = new SettingsReaderWriter(); + await settings.SaveSettings(); + } public ICommand ReaderSeletedCommand => new RelayCommand(ReaderSelected); private void ReaderSelected() @@ -55,11 +65,12 @@ private void ReaderSelected() ConnectToReaderCommand.Execute(null); } - public ICommand ConnectToReaderCommand => new RelayCommand(ConnectToReader); - private void ConnectToReader() + public IAsyncRelayCommand ConnectToReaderCommand => new AsyncRelayCommand(ConnectToReader); + private async Task ConnectToReader() { - //OnConnect?.Invoke(this); + await UpdateReaderStatusCommand.ExecuteAsync(true); + //OnConnect?.Invoke(this); switch (SelectedReader) { /* @@ -90,8 +101,12 @@ private void ConnectToReader() device = new ElatecNetProvider(); } - device.Connect(); - device.ReadChipPublic(); + if (device != null && !device.IsConnected) + { + await device.ConnectAsync(); + } + + var t = await device.ReadChipPublic(); } else { @@ -104,7 +119,7 @@ private void ConnectToReader() break; } - if (!string.IsNullOrEmpty(device?.GenericChip?.UID)) + if (device?.GenericChip?.Count > 0) { DefaultReader = Enum.GetName(typeof(ReaderTypes), SelectedReader); @@ -112,15 +127,49 @@ private void ConnectToReader() + '\n' + "UID: {0} " + '\n' - + "Type: {1}", - device.GenericChip.UID, - ResourceLoader.GetResource(string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), device.GenericChip.CardType)))); + + "Type: {1}", + device.GenericChip[0].UID, + ResourceLoader.GetResource(string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), device.GenericChip[0].CardType)))); } else { ReaderStatus = "no Reader / Card detected"; } + + await UpdateReaderStatusCommand.ExecuteAsync(false); + } + + /// + /// + /// + public IRelayCommand BeginUpdateCheckCommand => new RelayCommand(BeginUpdateCheck); + private void BeginUpdateCheck(bool isBusy) + { + if (OnBeginUpdateCheck != null) + { + OnBeginUpdateCheck(isBusy); + } + else + { + return; + } + } + + /// + /// + /// + public IAsyncRelayCommand UpdateReaderStatusCommand => new AsyncRelayCommand(UpdateReaderStatus); + private async Task UpdateReaderStatus(bool isBusy) + { + if (OnUpdateReaderStatus != null) + { + OnUpdateReaderStatus(isBusy); + } + else + { + return; + } } public ICommand ApplyAndExitCommand => new RelayCommand(Ok); @@ -157,6 +206,23 @@ public ReaderTypes SelectedReader set { selectedReader = value; + + if (device == null) + { + switch (selectedReader) + { + case ReaderTypes.Elatec: + device = new ElatecNetProvider(); + break; + case ReaderTypes.PCSC: + device = null; + break; + + default: + device = null; + break; + } + } } } private ReaderTypes selectedReader; @@ -246,15 +312,32 @@ public bool LoadOnStart public bool CheckOnStart { get => checkOnStart; - set => checkOnStart = value; + set + { + checkOnStart = value; + BeginUpdateCheckCommand.Execute(value); + } } private bool checkOnStart; -#region IUserDialogViewModel Implementation + #region IUserDialogViewModel Implementation + [XmlIgnore] + public Action OnBeginUpdateCheck { get; set; } + + [XmlIgnore] + public Action OnUpdateReaderStatus { get; set; } + + [XmlIgnore] public Action OnOk { get; set; } + + [XmlIgnore] public Action OnCancel { get; set; } + + [XmlIgnore] public Action OnConnect { get; set; } + + [XmlIgnore] public Action OnCloseRequest { get; set; } public bool IsModal { get; private set; } diff --git a/RFiDGear/ViewModel/SplashScreenViewModel.cs b/RFiDGear/ViewModel/SplashScreenViewModel.cs index 4086088..c708bd8 100644 --- a/RFiDGear/ViewModel/SplashScreenViewModel.cs +++ b/RFiDGear/ViewModel/SplashScreenViewModel.cs @@ -7,7 +7,7 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using RFiDGear.DataAccessLayer; using System; using System.Collections.Generic; diff --git a/RFiDGear/ViewModel/TaskSetupViewModels/CommonTaskViewModel.cs b/RFiDGear/ViewModel/TaskSetupViewModels/CommonTaskViewModel.cs index 2f2a936..499688d 100644 --- a/RFiDGear/ViewModel/TaskSetupViewModels/CommonTaskViewModel.cs +++ b/RFiDGear/ViewModel/TaskSetupViewModels/CommonTaskViewModel.cs @@ -8,13 +8,12 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using MvvmDialogs.ViewModels; +using Microsoft.Extensions.Logging; +using MVVMDialogs.ViewModels; using RFiDGear.DataAccessLayer; using RFiDGear.Model; -using Log4CSharp; - using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -23,8 +22,11 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; +using System.Windows; using System.Windows.Input; +using System.Windows.Controls; using System.Xml.Serialization; +using Org.BouncyCastle.Asn1.X509; namespace RFiDGear.ViewModel { @@ -34,8 +36,8 @@ namespace RFiDGear.ViewModel public class CommonTaskViewModel : ObservableObject, IUserDialogViewModel, IGenericTaskModel { #region Fields - private static readonly string FacilityName = "RFiDGear"; private static int IterCounter = 1; //Initial Value of Counter: How often have "this" been called (+1 per "run all tasks") + private readonly EventLog eventLog = new EventLog(Assembly.GetEntryAssembly().GetName().Name,"localhost", Assembly.GetEntryAssembly().GetName().Name); // The Counter could be replaced in an pdf by %n; %nn or %nnn. increased once per run all tasks: %n -> 1 on first execution private protected ReportReaderWriter reportReaderWriter; @@ -68,6 +70,8 @@ public class CommonTaskViewModel : ObservableObject, IUserDialogViewModel, IGene /// public CommonTaskViewModel() { + eventLog.Source = Assembly.GetEntryAssembly().GetName().Name; + CurrentTaskErrorLevel = ERROR.Empty; checkpoint = new Checkpoint(); @@ -78,7 +82,6 @@ public CommonTaskViewModel() IsLogicFuncTaskLogicFuncEnabled = true; IsLogicFuncTaskCountFuncEnabled = false; IsLogicFuncTaskCompareWithEnabled = false; - } /// @@ -119,8 +122,17 @@ public CommonTaskViewModel(object _selectedSetupViewModel, ObservableCollection< p.SetValue(this, p.GetValue(_selectedSetupViewModel)); } - var copy = Checkpoints; - Checkpoints = new ObservableCollection(copy); + var cpCopy = Checkpoints; + + if (cpCopy.Any(x => string.IsNullOrEmpty(x.CheckpointIndex))) + { + for (int i = 1; i <= cpCopy.Count; i++) + { + cpCopy[i - 1].CheckpointIndex = string.Format("{0:D3}", i); + } + } + + Checkpoints = new ObservableCollection(cpCopy); using (var reader = new ReportReaderWriter()) { @@ -149,16 +161,38 @@ public CommonTaskViewModel(object _selectedSetupViewModel, ObservableCollection< catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } AvailableTasks = _tasks; NumberOfCheckpoints = CustomConverter.GenerateStringSequence(0, 60).ToArray(); + + rowContextMenuItems = new ObservableCollection + { + new MenuItem() + { + Header = ResourceLoader.GetResource("contextMenuItemCopy"), + HorizontalContentAlignment = HorizontalAlignment.Center, + VerticalContentAlignment = VerticalAlignment.Center, + Command = CopySelectedCheckpoint, + IsEnabled = true + }, + + new MenuItem() + { + Header = ResourceLoader.GetResource("contextMenuItemPaste"), + HorizontalContentAlignment = HorizontalAlignment.Center, + VerticalContentAlignment = VerticalAlignment.Center, + Command = PasteSelectedCheckpoint, + IsEnabled = true + } + }; + } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } @@ -194,6 +228,13 @@ public bool IsFocused } private bool isFocused; + /// + /// expose contextmenu on row click + /// + [XmlIgnore] + public ObservableCollection RowContextMenu => rowContextMenuItems; + private readonly ObservableCollection rowContextMenuItems; + #endregion #region Dependency Properties @@ -511,6 +552,7 @@ public ObservableCollection Checkpoints /// /// /// + [XmlIgnore] public Checkpoint SelectedCheckpoint { get => selectedCheckpoint; @@ -521,11 +563,11 @@ public Checkpoint SelectedCheckpoint { Content = selectedCheckpoint.Content; } - OnPropertyChanged(nameof(SelectedCheckpoint)); } } private Checkpoint selectedCheckpoint; + private Checkpoint previouslySelectedCheckpoint; /// /// Collection of Tasks that were created. Select One to add a report entry. Called "Checkpoint" @@ -782,32 +824,57 @@ public string ProgramToExecute #endregion General Properties #region Commands + /// + /// + /// + public IAsyncRelayCommand SaveSettings => new AsyncRelayCommand(OnNewSaveSettingsCommand); + private async Task OnNewSaveSettingsCommand() + { + SettingsReaderWriter settings = new SettingsReaderWriter(); + await settings.SaveSettings(); + } + + [XmlIgnore] + public IAsyncRelayCommand CopySelectedCheckpoint => new AsyncRelayCommand(OnNewCopyCheckpointCommand); + private async Task OnNewCopyCheckpointCommand() + { + previouslySelectedCheckpoint = SelectedCheckpoint; + } + + [XmlIgnore] + public IAsyncRelayCommand PasteSelectedCheckpoint => new AsyncRelayCommand(OnNewPasteSelectedCheckpointCommand); + private async Task OnNewPasteSelectedCheckpointCommand() + { + await OnNewAddEditCheckpointCommand(previouslySelectedCheckpoint); + } /// /// /// - public ICommand CommandDelegator => new RelayCommand((x) => OnNewCommandDelegatorCall(x)); - private void OnNewCommandDelegatorCall(TaskType_CommonTask classicTaskType) + [XmlIgnore] + public IAsyncRelayCommand CommandDelegator => new AsyncRelayCommand((x) => OnNewCommandDelegatorCall(x)); + private async Task OnNewCommandDelegatorCall(TaskType_CommonTask commonTaskType) { - switch (classicTaskType) + switch (commonTaskType) { case TaskType_CommonTask.CreateReport: - OnNewWriteReportCommand(ReportReaderWriterToUse); + await OnNewWriteReportCommand(ReportReaderWriterToUse); break; case TaskType_CommonTask.CheckLogicCondition: - OnNewCheckLogicConditionCommand(); + await OnNewCheckLogicConditionCommand(); break; case TaskType_CommonTask.ExecuteProgram: - //OnNewExecuteProgramCommand(); + await OnNewExecuteProgramCommand(); break; default: break; } } - + /// /// /// + [XmlIgnore] public ICommand OpenReportTemplateCommand => new RelayCommand(OnNewOpenReportTemplateCommand); private void OnNewOpenReportTemplateCommand() { @@ -853,234 +920,227 @@ private void OnNewOpenReportTemplateCommand() } - catch { } + catch(Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Information); + } } /// /// /// - public ICommand WriteReportCommand => new RelayCommand(OnNewWriteReportCommand); - private void OnNewWriteReportCommand(ReportReaderWriter _reportReaderWriter) + public IAsyncRelayCommand WriteReportCommand => new AsyncRelayCommand(OnNewWriteReportCommand); + private async Task OnNewWriteReportCommand(ReportReaderWriter _reportReaderWriter) { CurrentTaskErrorLevel = ERROR.Empty; - var commonTask = new Task(() => + if (_reportReaderWriter != null) { - if (_reportReaderWriter != null) + var checkpointDictionary = new Dictionary(); + + // create a new key,value pair of taskpositions (int) <-> taskindex (string) + // (they could be different as because item at array position 0 can have index "100") + foreach (var rfidTaskObject in AvailableTasks) { - var checkpointDictionary = new Dictionary(); + checkpointDictionary.Add((rfidTaskObject as IGenericTaskModel).CurrentTaskIndex, AvailableTasks.IndexOf(rfidTaskObject)); + } - // create a new key,value pair of taskpositions (int) <-> taskindex (string) - // (they could be different as because item at array position 0 can have index "100") - foreach (var rfidTaskObject in AvailableTasks) + try + { + reportReaderWriter = _reportReaderWriter; + if (string.IsNullOrEmpty(reportReaderWriter.ReportTemplateFile)) { - checkpointDictionary.Add((rfidTaskObject as IGenericTaskModel).CurrentTaskIndex, AvailableTasks.IndexOf(rfidTaskObject)); + reportReaderWriter.ReportTemplateFile = ReportTemplatePath; } - try + if (!String.IsNullOrWhiteSpace(reportReaderWriter.ReportTemplateFile)) { - reportReaderWriter = _reportReaderWriter; - if (string.IsNullOrEmpty(reportReaderWriter.ReportTemplateFile)) - { - reportReaderWriter.ReportTemplateFile = ReportTemplatePath; - } - if (!String.IsNullOrWhiteSpace(reportReaderWriter.ReportTemplateFile)) + foreach (var checkpoint in Checkpoints) { - foreach (var checkpoint in Checkpoints) - { + var hasVariable = false; + var concatenate = false; - var hasVariable = false; - var concatenate = false; + var temporaryContent = checkpoint.Content; - var temporaryContent = checkpoint.Content; + if (temporaryContent.Contains("%UID")) + { + temporaryContent = temporaryContent.Replace("%UID", GenericChip?.UID ?? ""); + hasVariable = true; + } - if (temporaryContent.Contains("%UID")) + if (temporaryContent.Contains("%CHIPTYPE")) + { + temporaryContent = temporaryContent.Replace("%CHIPTYPE", ResourceLoader.GetResource( + string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), GenericChip?.CardType))) ?? ""); + hasVariable = true; + } + + if (temporaryContent.Contains("%SLAVECHIPTYPE")) + { + if (GenericChip != null && GenericChip.HasChilds == true) { - temporaryContent = temporaryContent.Replace("%UID", GenericChip?.UID ?? ""); + temporaryContent = temporaryContent.Replace("%SLAVECHIPTYPE", ResourceLoader.GetResource( + string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), GenericChip?.Childs[0]?.CardType))) ?? ""); hasVariable = true; } + } - if (temporaryContent.Contains("%CHIPTYPE")) + if (temporaryContent.Contains("%SLAVEUID")) + { + if (GenericChip != null && GenericChip.HasChilds == true) { - temporaryContent = temporaryContent.Replace("%CHIPTYPE", ResourceLoader.GetResource( - string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), GenericChip?.CardType))) ?? ""); + temporaryContent = temporaryContent.Replace("%SLAVEUID", GenericChip?.Childs[0]?.UID ?? ""); hasVariable = true; } + } - if (temporaryContent.Contains("%SLAVECHIPTYPE")) - { - if (GenericChip?.Child != null) - { - temporaryContent = temporaryContent.Replace("%SLAVECHIPTYPE", ResourceLoader.GetResource( - string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), GenericChip?.Child?.CardType))) ?? ""); - hasVariable = true; - } - } - - if (temporaryContent.Contains("%SLAVEUID")) - { - if (GenericChip?.Child != null) - { - temporaryContent = temporaryContent.Replace("%SLAVEUID", GenericChip?.Child?.UID ?? ""); - hasVariable = true; - } - } + if (temporaryContent.Contains("%DATETIME")) + { + temporaryContent = temporaryContent.Replace("%DATETIME", DateTime.Now.ToString(CultureInfo.CurrentCulture) ?? ""); + hasVariable = true; + } - if (temporaryContent.Contains("%DATETIME")) - { - temporaryContent = temporaryContent.Replace("%DATETIME", DateTime.Now.ToString(CultureInfo.CurrentCulture) ?? ""); - hasVariable = true; - } + if (temporaryContent.Contains("%DATE")) + { + temporaryContent = temporaryContent.Replace("%DATE", DateTime.Now.ToString("dd/MM/yyyy") ?? ""); + hasVariable = true; + } - if (temporaryContent.Contains("%DATE")) - { - temporaryContent = temporaryContent.Replace("%DATE", DateTime.Now.ToString("dd/MM/yyyy") ?? ""); - hasVariable = true; - } + if (temporaryContent.Contains("%FREEMEM")) + { + temporaryContent = temporaryContent.Replace("%FREEMEM", DesfireChip?.FreeMemory.ToString(CultureInfo.CurrentCulture) ?? ""); + hasVariable = true; + } - if (temporaryContent.Contains("%FREEMEM")) - { - temporaryContent = temporaryContent.Replace("%FREEMEM", DesfireChip?.FreeMemory.ToString(CultureInfo.CurrentCulture) ?? ""); - hasVariable = true; - } + if (temporaryContent.Contains("%FREECLASSICMEM")) + { + temporaryContent = temporaryContent.Replace("%FREECLASSICMEM", ClassicChip?.FreeMemory.ToString(CultureInfo.CurrentCulture) ?? ""); + hasVariable = true; + } - if (temporaryContent.Contains("%FREECLASSICMEM")) - { - temporaryContent = temporaryContent.Replace("%FREECLASSICMEM", ClassicChip?.FreeMemory.ToString(CultureInfo.CurrentCulture) ?? ""); - hasVariable = true; - } + if (temporaryContent.Contains("%LISTAPPS")) + { + temporaryContent = temporaryContent.Replace("%LISTAPPS", string.Join(", ", DesfireChip?.AppList.Select(x => x.appID)) ?? ""); + hasVariable = true; + } - if (temporaryContent.Contains("%LISTAPPS")) - { - temporaryContent = temporaryContent.Replace("%LISTAPPS", string.Join(", ", DesfireChip?.AppList.Select(x => x.appID)) ?? ""); - hasVariable = true; - } + if (temporaryContent.Contains("%COUNTAPPS")) + { + temporaryContent = temporaryContent.Replace("%COUNTAPPS", DesfireChip?.AppList?.Count.ToString(CultureInfo.CurrentCulture)); + hasVariable = true; + } - if (temporaryContent.Contains("%COUNTAPPS")) - { - temporaryContent = temporaryContent.Replace("%COUNTAPPS", DesfireChip?.AppList?.Count.ToString(CultureInfo.CurrentCulture)); - hasVariable = true; - } + if (temporaryContent.Contains("%CONCAT")) + { + temporaryContent = temporaryContent.Replace("%CONCAT ", string.Empty); + temporaryContent = temporaryContent.Replace("%CONCAT", string.Empty); + concatenate = true; + } - if (temporaryContent.Contains("%CONCAT")) - { - temporaryContent = temporaryContent.Replace("%CONCAT ", string.Empty); - temporaryContent = temporaryContent.Replace("%CONCAT", string.Empty); - concatenate = true; - } + if (temporaryContent.Contains("%NEWLINE")) + { + temporaryContent = temporaryContent.Replace("%NEWLINE ", "\n"); + temporaryContent = temporaryContent.Replace("%NEWLINE", "\n"); + concatenate = true; + } - if (temporaryContent.Contains("%NEWLINE")) - { - temporaryContent = temporaryContent.Replace("%NEWLINE ", "\n"); - temporaryContent = temporaryContent.Replace("%NEWLINE", "\n"); - concatenate = true; - } + if (temporaryContent.Contains("%nnn")) + { + temporaryContent = temporaryContent.Replace("%nnn", IterCounter.ToString("D3")); + hasVariable = true; + IterCounter++; + } - if (temporaryContent.Contains("%nnn")) - { - temporaryContent = temporaryContent.Replace("%nnn", IterCounter.ToString("D3")); - hasVariable = true; - IterCounter++; - } + if (temporaryContent.Contains("%nn")) + { + temporaryContent = temporaryContent.Replace("%nn", IterCounter.ToString("D2")); + hasVariable = true; + IterCounter++; + } - if (temporaryContent.Contains("%nn")) - { - temporaryContent = temporaryContent.Replace("%nn", IterCounter.ToString("D2")); - hasVariable = true; - IterCounter++; - } + if (temporaryContent.Contains("%n")) + { + temporaryContent = temporaryContent.Replace("%n", IterCounter.ToString("D1")); + hasVariable = true; + IterCounter++; + } - if (temporaryContent.Contains("%n")) + // the "dollar" indicates an external variable that should be replaced + if (temporaryContent.Contains("$")) + { + foreach (var kvArg in Args) { - temporaryContent = temporaryContent.Replace("%n", IterCounter.ToString("D1")); - hasVariable = true; - IterCounter++; + temporaryContent = temporaryContent.Replace(kvArg.Key, kvArg.Value); } - // the "dollar" indicates an external variable that should be replaced - if (temporaryContent.Contains("$")) - { - foreach(var kvArg in Args) - { - temporaryContent = temporaryContent.Replace(kvArg.Key, kvArg.Value); - } - - concatenate = true; - } + concatenate = true; + } - // Does the targeted Task Equals the selected TaskResult ? - // targeted Taskindex ist not "null" so check if targeted ERRORLEVEL fits current ERRORLEVEL - if (checkpointDictionary.TryGetValue(checkpoint.TaskIndex ?? "-1", out var targetIndex)) + // Does the targeted Task Equals the selected TaskResult ? + // targeted Taskindex ist not "null" so check if targeted ERRORLEVEL fits current ERRORLEVEL + // .ConfigureAwait(false) due to fileAccess + if (checkpointDictionary.TryGetValue(checkpoint.TaskIndex ?? "-1", out var targetIndex)) + { + if ((AvailableTasks[targetIndex] as IGenericTaskModel).CurrentTaskErrorLevel == checkpoint.ErrorLevel) { - if ((AvailableTasks[targetIndex] as IGenericTaskModel).CurrentTaskErrorLevel == checkpoint.ErrorLevel) + if (concatenate) { - if (concatenate) - { - reportReaderWriter.ConcatReportField(checkpoint.TemplateField, temporaryContent); - } - else - { - reportReaderWriter.SetReportField(checkpoint.TemplateField, hasVariable ? temporaryContent : checkpoint.Content); - } + await reportReaderWriter.ConcatReportField(checkpoint.TemplateField, temporaryContent); } else { - targetIndex++; + await reportReaderWriter.SetReportField(checkpoint.TemplateField, hasVariable ? temporaryContent : checkpoint.Content); } } + else + { + targetIndex++; + } + } - // The targeted Task does not Exist: Continue Execution anyway... + // The targeted Task does not Exist: Continue Execution anyway... + else + { + if (concatenate) + { + await reportReaderWriter.ConcatReportField(checkpoint.TemplateField, temporaryContent); + } else { - if (concatenate) - { - reportReaderWriter.ConcatReportField(checkpoint.TemplateField, temporaryContent); - } - else - { - reportReaderWriter.SetReportField(checkpoint.TemplateField, hasVariable ? temporaryContent : checkpoint.Content); - } + await reportReaderWriter.SetReportField(checkpoint.TemplateField, hasVariable ? temporaryContent : checkpoint.Content).ConfigureAwait(false); } } } } + } - catch (Exception e) - { - CurrentTaskErrorLevel = ERROR.IOError; - IsTaskCompletedSuccessfully = false; - OnPropertyChanged(nameof(TemplateFields)); + catch (Exception e) + { + CurrentTaskErrorLevel = ERROR.IOError; + IsTaskCompletedSuccessfully = false; + OnPropertyChanged(nameof(TemplateFields)); - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); - return; - } + return; + } - CurrentTaskErrorLevel = ERROR.NoError; - IsTaskCompletedSuccessfully = true; + CurrentTaskErrorLevel = ERROR.NoError; + IsTaskCompletedSuccessfully = true; - OnPropertyChanged(nameof(TemplateFields)); + OnPropertyChanged(nameof(TemplateFields)); - } - }); + } - if (CurrentTaskErrorLevel == ERROR.Empty) + if (CurrentTaskErrorLevel == ERROR.NoError) { - commonTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - commonTask.RunSynchronously(); + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; } return; @@ -1089,457 +1149,436 @@ private void OnNewWriteReportCommand(ReportReaderWriter _reportReaderWriter) /// /// /// - public ICommand CheckLogicCondition => new RelayCommand>(OnNewCheckLogicConditionCommand); - private void OnNewCheckLogicConditionCommand(ObservableCollection _tasks = null) + public IAsyncRelayCommand CheckLogicCondition => new AsyncRelayCommand>(OnNewCheckLogicConditionCommand); + private async Task OnNewCheckLogicConditionCommand(ObservableCollection _tasks = null) { CurrentTaskErrorLevel = ERROR.Empty; - var commonTask = - new Task(() => + CurrentTaskErrorLevel = await Task.Run(async () => + { + try { - try - { - var result = ERROR.Empty; - CurrentTaskErrorLevel = result; - - // here we are about to compare the results of the added "Checkpoints" in the "Check Condition" Task with the actual - // conditions from the live tasks + // here we are about to compare the results of the added "Checkpoints" in the "Check Condition" Task with the actual + // conditions from the live tasks - // lets fill a new vector with the results of all so far executed tasks... We will re-use the checkpoint objects for this - var results = new ObservableCollection(); + // lets fill a new vector with the results of all so far executed tasks... We will re-use the checkpoint objects for this + var results = new ObservableCollection(); - foreach (var task in _tasks) + foreach (var task in _tasks) + { + switch (task) { - switch (task) - { - case CommonTaskViewModel ssVM: - results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex, Content = ssVM.Content, CompareValue = ssVM.CompareValue }); - break; - case GenericChipTaskViewModel ssVM: - results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex }); - break; - case MifareClassicSetupViewModel ssVM: - results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex }); - break; - case MifareDesfireSetupViewModel ssVM: - results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex }); - break; - case MifareUltralightSetupViewModel ssVM: - results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex }); - break; - default: - break; - } + case CommonTaskViewModel ssVM: + results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex, Content = ssVM.Content, CompareValue = ssVM.CompareValue }); + break; + case GenericChipTaskViewModel ssVM: + results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex }); + break; + case MifareClassicSetupViewModel ssVM: + results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex }); + break; + case MifareDesfireSetupViewModel ssVM: + results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex }); + break; + case MifareUltralightSetupViewModel ssVM: + results.Add(new Checkpoint() { ErrorLevel = ssVM.CurrentTaskErrorLevel, TaskIndex = ssVM.CurrentTaskIndex }); + break; + default: + break; } + } - switch (SelectedLogicCondition) - { - case LOGIC_STATE.AND: + switch (SelectedLogicCondition) + { + case LOGIC_STATE.AND: - foreach (var cp in Checkpoints) + foreach (var cp in Checkpoints) + { + if (cp.ErrorLevel == results.Where(x => x.TaskIndex == cp.TaskIndex).Single().ErrorLevel) { - if (cp.ErrorLevel == results.Where(x => x.TaskIndex == cp.TaskIndex).Single().ErrorLevel) - { - continue; - } - else - { - CurrentTaskErrorLevel = ERROR.IsNotTrue; - return; - } - + continue; + } + else + { + return ERROR.IsNotTrue; } - result = ERROR.NoError; - break; + } + CurrentTaskErrorLevel = ERROR.NoError; + break; - case LOGIC_STATE.NAND: + case LOGIC_STATE.NAND: - foreach (var cp in Checkpoints) + foreach (var cp in Checkpoints) + { + for (var i = 0; i < Checkpoints.Count(); i++) { - for (var i = 0; i < Checkpoints.Count(); i++) + if (cp.ErrorLevel == Checkpoints[i].ErrorLevel) { - if (cp.ErrorLevel == Checkpoints[i].ErrorLevel) - { - continue; - } - else - { - result = ERROR.NoError; - break; - } + continue; + } + else + { + return ERROR.NoError; } } + } - result = ERROR.IsNotTrue; - break; + CurrentTaskErrorLevel = ERROR.IsNotTrue; + break; - case LOGIC_STATE.NOR: + case LOGIC_STATE.NOR: - foreach (var cp in Checkpoints) + foreach (var cp in Checkpoints) + { + for (var i = 0; i < Checkpoints.Count(); i++) { - for (var i = 0; i < Checkpoints.Count(); i++) + if (cp.ErrorLevel == Checkpoints[i].ErrorLevel) { - if (cp.ErrorLevel == Checkpoints[i].ErrorLevel) - { - result = ERROR.IsNotTrue; - break; - } + return ERROR.IsNotTrue; } } + } - result = ERROR.NoError; - break; + CurrentTaskErrorLevel = ERROR.NoError; + break; - case LOGIC_STATE.NOT: + case LOGIC_STATE.NOT: - break; + break; - case LOGIC_STATE.OR: + case LOGIC_STATE.OR: - foreach (var outerCP in Checkpoints) + foreach (var outerCP in Checkpoints) + { + foreach (var resultCP in results) { - foreach (var resultCP in results) + if (resultCP.TaskIndex == outerCP.TaskIndex && resultCP.ErrorLevel == outerCP.ErrorLevel) { - if (resultCP.TaskIndex == outerCP.TaskIndex && resultCP.ErrorLevel == outerCP.ErrorLevel) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - else - { - continue; - } + return ERROR.NoError; + } + else + { + continue; } } + } - result = ERROR.IsNotTrue; - break; + CurrentTaskErrorLevel = ERROR.IsNotTrue; + break; - case LOGIC_STATE.COUNT: + case LOGIC_STATE.COUNT: - var loops = 0; + var loops = 0; - foreach (var outerCP in Checkpoints) + foreach (var outerCP in Checkpoints) + { + foreach (var resultCP in results) { - foreach (var resultCP in results) + if (resultCP.TaskIndex == outerCP.TaskIndex && resultCP.ErrorLevel == outerCP.ErrorLevel) { - if (resultCP.TaskIndex == outerCP.TaskIndex && resultCP.ErrorLevel == outerCP.ErrorLevel) - { - loops++; - continue; - } - else - { - continue; - } + loops++; + continue; + } + else + { + continue; } } + } - switch (SelectedCounterTrigger) - { - case EQUALITY_OPERATOR.EQUAL: - if (loops == SelectedCheckpointCounterAsInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - - break; - - case EQUALITY_OPERATOR.LESS_OR_EQUAL: - if (loops <= SelectedCheckpointCounterAsInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - + switch (SelectedCounterTrigger) + { + case EQUALITY_OPERATOR.EQUAL: + if (loops == SelectedCheckpointCounterAsInt) + { + CurrentTaskErrorLevel = ERROR.NoError; break; + } + CurrentTaskErrorLevel = ERROR.IsNotTrue; + break; - case EQUALITY_OPERATOR.LESS_THAN: - if (loops < SelectedCheckpointCounterAsInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - + case EQUALITY_OPERATOR.LESS_OR_EQUAL: + if (loops <= SelectedCheckpointCounterAsInt) + { + CurrentTaskErrorLevel = ERROR.NoError; break; + } + CurrentTaskErrorLevel = ERROR.IsNotTrue; + break; - case EQUALITY_OPERATOR.MORE_OR_EQUAL: - if (loops >= SelectedCheckpointCounterAsInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - + case EQUALITY_OPERATOR.LESS_THAN: + if (loops < SelectedCheckpointCounterAsInt) + { + CurrentTaskErrorLevel = ERROR.NoError; break; + } + CurrentTaskErrorLevel = ERROR.IsNotTrue; + break; - case EQUALITY_OPERATOR.MORE_THAN: - if (loops > SelectedCheckpointCounterAsInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - + case EQUALITY_OPERATOR.MORE_OR_EQUAL: + if (loops >= SelectedCheckpointCounterAsInt) + { + CurrentTaskErrorLevel = ERROR.NoError; break; + } + CurrentTaskErrorLevel = ERROR.IsNotTrue; + break; - default: + case EQUALITY_OPERATOR.MORE_THAN: + if (loops > SelectedCheckpointCounterAsInt) + { + CurrentTaskErrorLevel = ERROR.NoError; break; - } + } + CurrentTaskErrorLevel = ERROR.IsNotTrue; + break; + default: + CurrentTaskErrorLevel = ERROR.IsNotTrue; + break; + } - result = ERROR.IsNotTrue; - break; + break; - case LOGIC_STATE.COMPARE: //Compare 'TaskResult Content' + case LOGIC_STATE.COMPARE: //Compare 'TaskResult Content' - try + try + { + if (CompareValue.Contains(">=")) { - if (CompareValue.Contains(">=")) - { - var comparetemp = CompareValue.Replace(" ", string.Empty).Replace(">", string.Empty).Split('='); + var comparetemp = CompareValue.Replace(" ", string.Empty).Replace(">", string.Empty).Split('='); - //assume 2 values to compare - if (comparetemp.Length == 2) + //assume 2 values to compare + if (comparetemp.Length == 2) + { + switch (comparetemp[0]) { - switch (comparetemp[0]) - { - case "%FREEMEM": - uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out var compareValueAsUInt); - - if (DesfireChip?.FreeMemory >= compareValueAsUInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - - else - { - CurrentTaskErrorLevel = ERROR.IsNotTrue; - } + case "%FREEMEM": + uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out var compareValueAsUInt); + if (DesfireChip?.FreeMemory >= compareValueAsUInt) + { + CurrentTaskErrorLevel = ERROR.NoError; break; + } - case "%COUNTAPPS": - uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); + else + { + CurrentTaskErrorLevel = ERROR.IsNotTrue; + } - if (DesfireChip?.AppIDs.Count() >= compareValueAsUInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } + break; - else - { - CurrentTaskErrorLevel = ERROR.IsNotTrue; - } + case "%COUNTAPPS": + uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); + if (DesfireChip?.AppIDs.Count() >= compareValueAsUInt) + { + CurrentTaskErrorLevel = ERROR.NoError; break; + } - default: - break; - } + else + { + CurrentTaskErrorLevel = ERROR.IsNotTrue; + } + + break; + + default: + break; } } + } - else if (CompareValue.Contains("<=")) - { - var comparetemp = CompareValue.Replace(" ", string.Empty).Replace("<", string.Empty).Split('='); + else if (CompareValue.Contains("<=")) + { + var comparetemp = CompareValue.Replace(" ", string.Empty).Replace("<", string.Empty).Split('='); - //assume 2 values to compare - if (comparetemp.Length == 2) + //assume 2 values to compare + if (comparetemp.Length == 2) + { + switch (comparetemp[0]) { - switch (comparetemp[0]) - { - case "%FREEMEM": - uint compareValueAsUInt; - uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); + case "%FREEMEM": + uint compareValueAsUInt; + uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); - if (DesfireChip?.FreeMemory <= compareValueAsUInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } + if (DesfireChip?.FreeMemory <= compareValueAsUInt) + { + CurrentTaskErrorLevel = ERROR.NoError; + break; + } - else - { - CurrentTaskErrorLevel = ERROR.IsNotTrue; - } + else + { + CurrentTaskErrorLevel = ERROR.IsNotTrue; + } - break; + break; - default: - break; - } + default: + break; } } + } - else if (CompareValue.Contains("!=")) - { - var comparetemp = CompareValue.Split(new string[] { "!=" }, 2, StringSplitOptions.None); + else if (CompareValue.Contains("!=")) + { + var comparetemp = CompareValue.Split(new string[] { "!=" }, 2, StringSplitOptions.None); - //assume 2 values to compare - if (comparetemp.Length == 2) + //assume 2 values to compare + if (comparetemp.Length == 2) + { + // the "dollar" indicates an external variable that should be replaced + if (comparetemp[0].Contains("$")) { - // the "dollar" indicates an external variable that should be replaced - if (comparetemp[0].Contains("$")) + foreach (var kvArg in Args) { - foreach (var kvArg in Args) + if (Args[comparetemp[0]] != comparetemp[1]) { - if (Args[comparetemp[0]] != comparetemp[1]) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } + return ERROR.NoError; } } + CurrentTaskErrorLevel = ERROR.IsNotTrue; + } - switch (comparetemp[0]) - { - case "%FREEMEM": - uint compareValueAsUInt; - uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); - - if (compareValueAsUInt == DesfireChip?.FreeMemory) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - - else - { - CurrentTaskErrorLevel = ERROR.IsNotTrue; - } + switch (comparetemp[0]) + { + case "%FREEMEM": + uint compareValueAsUInt; + uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); + if (compareValueAsUInt == DesfireChip?.FreeMemory) + { + CurrentTaskErrorLevel = ERROR.NoError; break; + } - case "%COUNTAPPS": - uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); + else + { + CurrentTaskErrorLevel = ERROR.IsNotTrue; + } - if (DesfireChip?.AppIDs.Count() >= compareValueAsUInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } + break; - break; + case "%COUNTAPPS": + uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); - default: + if (DesfireChip?.AppIDs.Count() >= compareValueAsUInt) + { + CurrentTaskErrorLevel = ERROR.NoError; break; - } + } + break; + default: + break; } + + } + } - else if (CompareValue.Contains("==")) - { - var comparetemp = CompareValue.Split(new string[] { "==" }, 2, StringSplitOptions.None); + else if (CompareValue.Contains("==")) + { + var comparetemp = CompareValue.Split(new string[] { "==" }, 2, StringSplitOptions.None); - //assume 2 values to compare - if (comparetemp.Length == 2) + //assume 2 values to compare + if (comparetemp.Length == 2) + { + // the "dollar" indicates an external variable that should be replaced + if (comparetemp[0].Contains("$")) { - // the "dollar" indicates an external variable that should be replaced - if (comparetemp[0].Contains("$")) + foreach (var kvArg in Args) { - foreach (var kvArg in Args) + if (Args[comparetemp[0]] == comparetemp[1]) { - if (Args[comparetemp[0]] == comparetemp[1]) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } + return ERROR.NoError; } } + CurrentTaskErrorLevel = ERROR.IsNotTrue; + } - switch (comparetemp[0]) - { - case "%FREEMEM": - uint compareValueAsUInt; - uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); - - if (compareValueAsUInt == DesfireChip?.FreeMemory) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - - else - { - CurrentTaskErrorLevel = ERROR.IsNotTrue; - } + switch (comparetemp[0]) + { + case "%FREEMEM": + uint compareValueAsUInt; + uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); + if (compareValueAsUInt == DesfireChip?.FreeMemory) + { + CurrentTaskErrorLevel = ERROR.NoError; break; + } - case "%COUNTAPPS": - uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); + else + { + CurrentTaskErrorLevel = ERROR.IsNotTrue; + } - if (DesfireChip?.AppIDs.Count() >= compareValueAsUInt) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } + break; - break; + case "%COUNTAPPS": + uint.TryParse(new string(comparetemp[1].Where(c => Char.IsDigit(c)).ToArray()), out compareValueAsUInt); - default: + if (DesfireChip?.AppIDs.Count() >= compareValueAsUInt) + { + CurrentTaskErrorLevel = ERROR.NoError; break; - } + } + break; + default: + break; } - } - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } - result = ERROR.IsNotTrue; + } + } + } - break; + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + } - default: - break; - } + break; - CurrentTaskErrorLevel = result; - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); + default: + break; } + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + } - }); + return CurrentTaskErrorLevel; + }); - if (CurrentTaskErrorLevel == ERROR.Empty) + if (CurrentTaskErrorLevel == ERROR.NoError) { - commonTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - commonTask.RunSynchronously(); + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; } - return; + return CurrentTaskErrorLevel; } /// /// /// - public ICommand ExecuteProgramCommand => new RelayCommand(OnNewExecuteProgramCommand); - private void OnNewExecuteProgramCommand() + public IAsyncRelayCommand ExecuteProgramCommand => new AsyncRelayCommand(OnNewExecuteProgramCommand); + private async Task OnNewExecuteProgramCommand() { try { @@ -1631,30 +1670,62 @@ private void OnNewExecuteProgramCommand() { CurrentTaskErrorLevel = ERROR.IsNotTrue; IsTaskCompletedSuccessfully = false; - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } /// /// /// - public ICommand AddEditCheckpointCommand => new RelayCommand(OnNewAddEditCheckpointCommand); - private void OnNewAddEditCheckpointCommand() + public IAsyncRelayCommand AddEditCheckpointCommand => new AsyncRelayCommand(OnNewAddEditCheckpointCommand); + private async Task OnNewAddEditCheckpointCommand() + { + await OnNewAddEditCheckpointCommand(SelectedCheckpoint); + } + + private async Task OnNewAddEditCheckpointCommand(Checkpoint cpTarget) { try { checkpoint = new Checkpoint { - ErrorLevel = ERROR.Empty + ErrorLevel = ERROR.Empty, + CheckpointIndex = "", + TemplateField = "", + UUID = new Random().Next(), + Content = "", + CompareValue = "", + TaskIndex = "", }; if (SelectedTaskType == TaskType_CommonTask.CreateReport) { - checkpoint.TaskIndex = ""; - checkpoint.ErrorLevel = ERROR.Empty; - checkpoint.Content = Content; + if (cpTarget != null) + { + var currIndex = Checkpoints.IndexOf(SelectedCheckpoint); + + checkpoint = new Checkpoint + { + ErrorLevel = cpTarget.ErrorLevel, + CheckpointIndex = cpTarget.CheckpointIndex, + TemplateField = cpTarget.TemplateField, + UUID = new Random().Next(), + Content = cpTarget.Content, + CompareValue = cpTarget.CompareValue, + TaskIndex = cpTarget.TaskIndex, + }; + + checkpoint.CheckpointIndex = string.Format("{0:D3}", currIndex + 1); + + for (var i = currIndex; i < Checkpoints.Count; i++) + { + Checkpoints[i].CheckpointIndex = string.Format("{0:D3}", Checkpoints[i].CheckpointIndexAsInt + 1); + } + } Checkpoints.Add(checkpoint); + Checkpoints = new ObservableCollection(Checkpoints.OrderBy(x => x.CheckpointIndexAsInt)); + SelectedCheckpoint = checkpoint; } else if (SelectedTaskType == TaskType_CommonTask.CheckLogicCondition) @@ -1672,7 +1743,7 @@ private void OnNewAddEditCheckpointCommand() catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } return; @@ -1684,7 +1755,18 @@ private void OnNewAddEditCheckpointCommand() public ICommand RemoveCheckpointCommand => new RelayCommand(OnNewRemoveCheckpointCommand); private void OnNewRemoveCheckpointCommand() { - Checkpoints.Remove(SelectedCheckpoint); + if (SelectedCheckpoint != null) + { + var currIndex = Checkpoints.IndexOf(SelectedCheckpoint); + + Checkpoints.Remove(SelectedCheckpoint); + + for (int i = currIndex; i < Checkpoints.Count - 1; i++) + { + Checkpoints[i].CheckpointIndex = string.Format("{0:D3}", i + 1); + } + } + Checkpoints = new ObservableCollection(Checkpoints.OrderBy(x => x.CheckpointIndexAsInt)); } #endregion Commands diff --git a/RFiDGear/ViewModel/TaskSetupViewModels/GenericChipTaskViewModel.cs b/RFiDGear/ViewModel/TaskSetupViewModels/GenericChipTaskViewModel.cs index ba2c781..ea3e10e 100644 --- a/RFiDGear/ViewModel/TaskSetupViewModels/GenericChipTaskViewModel.cs +++ b/RFiDGear/ViewModel/TaskSetupViewModels/GenericChipTaskViewModel.cs @@ -9,13 +9,13 @@ using CommunityToolkit.Mvvm.Input; using MefMvvm.SharedContracts; using MefMvvm.SharedContracts.ViewModel; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using RFiDGear.DataAccessLayer.Remote.FromIO; using RFiDGear.DataAccessLayer; using RFiDGear.Model; -using Log4CSharp; + using System; using System.Collections.Generic; @@ -26,6 +26,9 @@ using System.Windows.Input; using System.Xml.Serialization; using Elatec.NET; +using System.Linq; +using LibLogicalAccess; +using System.Diagnostics; namespace RFiDGear.ViewModel { @@ -35,9 +38,8 @@ namespace RFiDGear.ViewModel public class GenericChipTaskViewModel : ObservableObject, IUserDialogViewModel, IGenericTaskModel { #region fields - private static readonly string FacilityName = "RFiDGear"; + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); - private protected SettingsReaderWriter settings = new SettingsReaderWriter(); private protected ReportReaderWriter reportReaderWriter; private protected Checkpoint checkpoint; private protected readonly ObservableCollection _availableTasks; @@ -94,7 +96,7 @@ public GenericChipTaskViewModel(object _selectedSetupViewModel, ObservableCollec } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } @@ -307,12 +309,6 @@ public string SelectedTaskDescription } private string selectedTaskDescription; - /// - /// - /// - [XmlIgnore] - public SettingsReaderWriter Settings => settings; - #endregion General Properties #region Commands @@ -320,234 +316,191 @@ public string SelectedTaskDescription /// /// /// - public ICommand CheckChipType => new RelayCommand(OnNewCheckChipTypeCommand); - private void OnNewCheckChipTypeCommand() + public IAsyncRelayCommand SaveSettings => new AsyncRelayCommand(OnNewSaveSettingsCommand); + private async Task OnNewSaveSettingsCommand() + { + SettingsReaderWriter settings = new SettingsReaderWriter(); + await settings.SaveSettings(); + } + + /// + /// + /// + public IAsyncRelayCommand CheckChipType => new AsyncRelayCommand>((x) => OnNewCheckChipTypeCommand(x)); + + private async Task OnNewCheckChipTypeCommand() + { + return await OnNewCheckChipTypeCommand(null); + } + private async Task OnNewCheckChipTypeCommand(List chipList) { CurrentTaskErrorLevel = ERROR.Empty; - var genericChipTask = - new Task(() => + List chipListToUse; + + using (var device = ReaderDevice.Instance) + { + if (device != null) { - using (var device = ReaderDevice.Instance) + var result = ERROR.Empty; + + if (chipList != null) { - if (device != null) + chipListToUse = chipList; + } + else + { + await device.ReadChipPublic(); + chipListToUse = device.GenericChip; + } + + if (((int)SelectedChipType | 0xF000) == 0xF000) // Do NOT Check for explicit Subtype e.g desfire ev1 >2k, 4k, 8k etc.< + { + if (chipListToUse.Where(x => (CARD_TYPE)((int)x.CardType & 0xF000) == (CARD_TYPE)SelectedChipType).Any()) { - var result = ERROR.Empty; - - if (device.GenericChip.CardType == SelectedChipType) - { - result = ERROR.NoError; - } - else if (Enum.GetName(typeof(CARD_TYPE), SelectedChipType).ToLower(CultureInfo.CurrentCulture).Contains("desfire")) - { - result = ERROR.IsNotTrue; - - switch (SelectedChipType) - { - case CARD_TYPE.DESFire: - if (device.GenericChip.CardType == CARD_TYPE.DESFire_256 || - device.GenericChip.CardType == CARD_TYPE.DESFire_2K || - device.GenericChip.CardType == CARD_TYPE.DESFire_4K) - { - result = ERROR.NoError; - } - break; - case CARD_TYPE.DESFireEV1: - if (device.GenericChip.CardType == CARD_TYPE.DESFireEV1_256 || - device.GenericChip.CardType == CARD_TYPE.DESFireEV1_2K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV1_4K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV1_8K) - { - result = ERROR.NoError; - } - break; - case CARD_TYPE.DESFireEV2: - if (device.GenericChip.CardType == CARD_TYPE.DESFireEV2_2K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV2_4K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV2_8K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV2_16K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV2_32K) - { - result = ERROR.NoError; - } - break; - case CARD_TYPE.DESFireEV3: - if (device.GenericChip.CardType == CARD_TYPE.DESFireEV3_2K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV3_4K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV3_8K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV3_16K || - device.GenericChip.CardType == CARD_TYPE.DESFireEV3_32K) - { - result = ERROR.NoError; - } - break; - - default: - result = ERROR.IsNotTrue; - break; - } - } - else - { - result = ERROR.IsNotTrue; - } - - CurrentTaskErrorLevel = result; - return; + result = ERROR.NoError; } else { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; + result = ERROR.IsNotTrue; } - } - }); - if (CurrentTaskErrorLevel == ERROR.Empty) - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - - genericChipTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; } - else + else // Take explicit Type into account { - IsTaskCompletedSuccessfully = false; + if (chipListToUse.Where(x => x.CardType == SelectedChipType).Any()) + { + result = ERROR.NoError; + } + else + { + result = ERROR.IsNotTrue; + } } - }); - genericChipTask.RunSynchronously(); + + CurrentTaskErrorLevel = result; + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + } + } + + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; } - return; + return CurrentTaskErrorLevel; } /// /// /// - public ICommand CheckChipIsMultiTecChip => new RelayCommand(OnNewCheckChipIsMultiTecChipCommand); - private void OnNewCheckChipIsMultiTecChipCommand() + public IAsyncRelayCommand CheckChipIsMultiTecChip => new AsyncRelayCommand>((x) => OnNewCheckChipIsMultiTecChipCommand(x)); + private async Task OnNewCheckChipIsMultiTecChipCommand(List chipList) { CurrentTaskErrorLevel = ERROR.Empty; - var genericChipTask = - new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - var result = device.ReadChipPublic(); - - if (result == ERROR.NoError) - { - - if (device.GenericChip.Child != null) - { - result = ERROR.NoError; - } - else - { - result = ERROR.IsNotTrue; - } + List chipListToUse; - CurrentTaskErrorLevel = result; - return; + using (var device = ReaderDevice.Instance) + { + if (device != null) + { + var result = ERROR.Empty; - } - } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } + if (chipList != null) + { + chipListToUse = chipList.FirstOrDefault().Childs; + } + else + { + result = await device.ReadChipPublic(); + chipListToUse = device.GenericChip; } - }); - if (CurrentTaskErrorLevel == ERROR.Empty) - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - genericChipTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) + if (chipListToUse != null && chipListToUse.Count >= 1) { - IsTaskCompletedSuccessfully = true; + result = ERROR.NoError; } else { - IsTaskCompletedSuccessfully = false; + result = ERROR.IsNotTrue; } - }); - genericChipTask.RunSynchronously(); + + CurrentTaskErrorLevel = result; + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + } + } + + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; } - return; + return CurrentTaskErrorLevel; } /// /// /// - public ICommand CheckChipUID => new RelayCommand(OnNewCheckChipUIDCommand); - private void OnNewCheckChipUIDCommand() + public ICommand CheckChipUID => new AsyncRelayCommand(OnNewCheckChipUIDCommand); + private async Task OnNewCheckChipUIDCommand() { CurrentTaskErrorLevel = ERROR.Empty; - var genericChipTask = - new Task(() => + using (var device = ReaderDevice.Instance) + { + if (device != null) { - using (var device = ReaderDevice.Instance) + var result = await device.ReadChipPublic(); + + if (result == ERROR.NoError) { - if (device != null) + if (device.GenericChip + .Where(x => x.UID.ToLower(CultureInfo.CurrentCulture) == SelectedUIDOfChip.ToLower(CultureInfo.CurrentCulture)) + .Any()) { - var result = device.ReadChipPublic(); - - if (result == ERROR.NoError) - { - - if (device.GenericChip.UID.ToLower(CultureInfo.CurrentCulture) == SelectedUIDOfChip.ToLower(CultureInfo.CurrentCulture)) - { - result = ERROR.NoError; - } - else - { - result = ERROR.IsNotTrue; - } - - CurrentTaskErrorLevel = result; - return; - - } + result = ERROR.NoError; } else { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; + result = ERROR.IsNotTrue; } - } - }); - if (CurrentTaskErrorLevel == ERROR.Empty) - { - CurrentTaskErrorLevel = ERROR.NotReadyError; + CurrentTaskErrorLevel = result; - genericChipTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; } - }); - genericChipTask.RunSynchronously(); + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + } + } + + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; } - return; + return CurrentTaskErrorLevel; } #endregion @@ -570,13 +523,13 @@ public virtual void RequestClose() public event EventHandler DialogClosing; - public ICommand OKCommand => new RelayCommand(Ok); + public IAsyncRelayCommand OKCommand => new AsyncRelayCommand(Ok); - protected virtual void Ok() + protected async virtual Task Ok() { if (OnOk != null) { - OnOk(this); + await OnOk(this); } else { @@ -613,7 +566,7 @@ protected virtual void Auth() } [XmlIgnore] - public Action OnOk { get; set; } + public Func OnOk { get; set; } [XmlIgnore] public Action OnCancel { get; set; } diff --git a/RFiDGear/ViewModel/TaskSetupViewModels/MifareClassicSetupViewModel.cs b/RFiDGear/ViewModel/TaskSetupViewModels/MifareClassicSetupViewModel.cs index d4a9383..0767b33 100644 --- a/RFiDGear/ViewModel/TaskSetupViewModels/MifareClassicSetupViewModel.cs +++ b/RFiDGear/ViewModel/TaskSetupViewModels/MifareClassicSetupViewModel.cs @@ -8,18 +8,17 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using MefMvvm.SharedContracts; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using RFiDGear.DataAccessLayer.Remote.FromIO; using RFiDGear.DataAccessLayer; using RFiDGear.Model; -using Log4CSharp; - using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; @@ -36,8 +35,7 @@ namespace RFiDGear.ViewModel public class MifareClassicSetupViewModel : ObservableObject, IUserDialogViewModel, IGenericTaskModel { #region Fields - - private readonly string FacilityName = "RFiDGear"; + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private readonly ObservableCollection dataBlock_AccessBits = new ObservableCollection (new[] @@ -169,8 +167,6 @@ public class MifareClassicSetupViewModel : ObservableObject, IUserDialogViewMode private MifareClassicSectorModel sectorModel; - private readonly SettingsReaderWriter settings = new SettingsReaderWriter(); - private byte madGPB = 0xC1; #endregion fields @@ -220,6 +216,8 @@ public MifareClassicSetupViewModel(object _selectedSetupViewModel, ObservableCol { try { + SettingsReaderWriter settings = new SettingsReaderWriter(); + sectorModel = new MifareClassicSectorModel(4, AccessCondition_MifareClassicSectorTrailer.NotAllowed, AccessCondition_MifareClassicSectorTrailer.Allowed_With_KeyA, @@ -323,7 +321,7 @@ public MifareClassicSetupViewModel(object _selectedSetupViewModel, ObservableCol } catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } @@ -837,12 +835,6 @@ public string SelectedTaskDescription } private string selectedAccessBitsTaskDescription; - /// - /// - /// - [XmlIgnore] - public SettingsReaderWriter Settings => settings; - /// /// /// @@ -962,6 +954,8 @@ public string ClassicKeyAKeyCurrent get => classicKeyAKeyCurrent; set { + SettingsReaderWriter settings = new SettingsReaderWriter(); + classicKeyAKeyCurrent = value.Length > 12 ? value.ToUpper(CultureInfo.CurrentCulture).Remove(12, value.Length - 12) : value.ToUpper(CultureInfo.CurrentCulture); IsValidClassicKeyAKeyCurrent = (CustomConverter.IsInHexFormat(classicKeyAKeyCurrent) && classicKeyAKeyCurrent.Length == 12); @@ -1011,6 +1005,8 @@ public string ClassicKeyBKeyCurrent get => classicKeyBKeyCurrent; set { + SettingsReaderWriter settings = new SettingsReaderWriter(); + classicKeyBKeyCurrent = value.Length > 12 ? value.ToUpper(CultureInfo.CurrentCulture).Remove(12, value.Length - 12) : value.ToUpper(CultureInfo.CurrentCulture); IsValidClassicKeyBKeyCurrent = (CustomConverter.IsInHexFormat(classicKeyBKeyCurrent) && classicKeyBKeyCurrent.Length == 12); @@ -1097,6 +1093,8 @@ public string SelectedClassicSectorCurrent { if (int.TryParse(value, out selectedClassicSectorCurrentAsInt)) { + SettingsReaderWriter settings = new SettingsReaderWriter(); + selectedClassicSectorCurrent = value; if (selectedClassicSectorCurrentAsInt > 31) @@ -1620,19 +1618,29 @@ public bool? IsValidClassicKeyBKeyTarget #region Commands - public ICommand CommandDelegator => new RelayCommand((x) => OnNewCommandDelegatorCall(x)); - private void OnNewCommandDelegatorCall(TaskType_MifareClassicTask classicTaskType) + /// + /// + /// + public IAsyncRelayCommand SaveSettings => new AsyncRelayCommand(OnNewSaveSettingsCommand); + private async Task OnNewSaveSettingsCommand() + { + SettingsReaderWriter settings = new SettingsReaderWriter(); + await settings.SaveSettings(); + } + + public IAsyncRelayCommand CommandDelegator => new AsyncRelayCommand((x) => OnNewCommandDelegatorCall(x)); + private async Task OnNewCommandDelegatorCall(TaskType_MifareClassicTask classicTaskType) { switch(classicTaskType) { case TaskType_MifareClassicTask.ReadData: - OnNewReadDataCommand(); + await OnNewReadDataCommand(); break; case TaskType_MifareClassicTask.WriteData: - OnNewWriteDataCommand(); + await OnNewWriteDataCommand(); break; case TaskType_MifareClassicTask.EmptyCheck: - OnNewCheckEmptyCommand(); + await OnNewCheckEmptyCommand(); break; default: break; @@ -1642,317 +1650,287 @@ private void OnNewCommandDelegatorCall(TaskType_MifareClassicTask classicTaskTyp /// /// Check if DataBlock 0, 1 and 2 contain all 0 and if Authentication with KeyA = 6xFF works /// - public ICommand CheckEmptyCommand => new RelayCommand(OnNewCheckEmptyCommand); - private protected void OnNewCheckEmptyCommand() + public ICommand CheckEmptyCommand => new AsyncRelayCommand(OnNewCheckEmptyCommand); + private protected async Task OnNewCheckEmptyCommand() { CurrentTaskErrorLevel = ERROR.Empty; - var classicTask = - new Task(() => + using (var device = ReaderDevice.Instance) + { + if (device != null) { - using (var device = ReaderDevice.Instance) + StatusText += string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (await device.ReadMifareClassicSingleSector( + selectedClassicSectorCurrentAsInt, + ClassicKeyAKeyCurrent, + ClassicKeyBKeyCurrent) == ERROR.NoError) { - if (device != null) - { - StatusText += string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + StatusText += string.Format("{0}: Success for Sector: {1}\n", DateTime.Now, selectedClassicSectorCurrentAsInt); - if (device.ReadMifareClassicSingleSector( - selectedClassicSectorCurrentAsInt, - ClassicKeyAKeyCurrent, - ClassicKeyBKeyCurrent) == ERROR.NoError) + for (var i = 0; i < device.Sector.DataBlock.Count - 1; i++) + { + for (var j = 0; j < device.Sector.DataBlock[i].Data.Length; j++) { - StatusText += string.Format("{0}: Success for Sector: {1}\n", DateTime.Now, selectedClassicSectorCurrentAsInt); - - for (var i = 0; i < device.Sector.DataBlock.Count - 1; i++) + if (device.Sector.DataBlock[i].Data[j] == 0 && device.Sector.IsAuthenticated == true) { - for(var j = 0; j < device.Sector.DataBlock[i].Data.Length; j++) - { - if(device.Sector.DataBlock[i].Data[j] == 0 && device.Sector.IsAuthenticated == true) - { - continue; - } - else - { - CurrentTaskErrorLevel = ERROR.IsNotTrue; - return; - } - } + continue; + } + else + { + CurrentTaskErrorLevel = ERROR.IsNotTrue; + break; } - - CurrentTaskErrorLevel = ERROR.NoError; - - } - - else - { - StatusText += string.Format("{0}: Unable to Authenticate to Sector: {1} using specified Keys\n", DateTime.Now, selectedClassicSectorCurrentAsInt); - CurrentTaskErrorLevel = ERROR.AuthenticationError; - return; } } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } + CurrentTaskErrorLevel = ERROR.NoError; - OnPropertyChanged(nameof(ChildNodeViewModelTemp)); - - return; } - }); - if (CurrentTaskErrorLevel == ERROR.Empty) - { - classicTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } else { - IsTaskCompletedSuccessfully = false; + StatusText += string.Format("{0}: Unable to Authenticate to Sector: {1} using specified Keys\n", DateTime.Now, selectedClassicSectorCurrentAsInt); + CurrentTaskErrorLevel = ERROR.AuthenticationError; } - }); + } - classicTask.RunSynchronously(); + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + return; + } + + OnPropertyChanged(nameof(ChildNodeViewModelTemp)); + + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + + return; } } /// /// Read Data to Memory /// - public ICommand ReadDataCommand => new RelayCommand(OnNewReadDataCommand); - private protected void OnNewReadDataCommand() + public ICommand ReadDataCommand => new AsyncRelayCommand(OnNewReadDataCommand); + private protected async Task OnNewReadDataCommand() { CurrentTaskErrorLevel = ERROR.Empty; - var classicTask = - new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - StatusText += string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (!useMAD) - { - if (device.ReadMifareClassicSingleSector( - selectedClassicSectorCurrentAsInt, - ClassicKeyAKeyCurrent, - ClassicKeyBKeyCurrent) == ERROR.NoError) - { + using (var device = ReaderDevice.Instance) + { + if (device != null) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); - childNodeViewModelFromChip.SectorNumber = selectedClassicSectorCurrentAsInt; - childNodeViewModelTemp.SectorNumber = selectedClassicSectorCurrentAsInt; + StatusText += string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - StatusText += string.Format("{0}: Success for Sector: {1}\n", DateTime.Now, selectedClassicSectorCurrentAsInt); + if (!useMAD) + { + if (await device.ReadMifareClassicSingleSector( + selectedClassicSectorCurrentAsInt, + ClassicKeyAKeyCurrent, + ClassicKeyBKeyCurrent) == ERROR.NoError) + { - for (var i = 0; i < device.Sector.DataBlock.Count; i++) - { - childNodeViewModelFromChip.Children[i].DataBlockNumber = i; - childNodeViewModelTemp.Children[i].DataBlockNumber = i; + childNodeViewModelFromChip.SectorNumber = selectedClassicSectorCurrentAsInt; + childNodeViewModelTemp.SectorNumber = selectedClassicSectorCurrentAsInt; - childNodeViewModelFromChip.Children[i].MifareClassicDataBlock.DataBlockNumberChipBased = device.Sector.DataBlock.First(x => x.DataBlockNumberSectorBased == i).DataBlockNumberChipBased; + StatusText += string.Format("{0}: Success for Sector: {1}\n", DateTime.Now, selectedClassicSectorCurrentAsInt); - if (device.Sector.DataBlock[i].IsAuthenticated) - { - StatusText += string.Format("{0}: \tSuccess for Blocknumber: {1} Data: {2}\n", DateTime.Now, device.Sector.DataBlock[i].DataBlockNumberChipBased, CustomConverter.HexToString(device.Sector.DataBlock[i].Data)); - childNodeViewModelFromChip.Children.First(x => x.DataBlockNumber == i).MifareClassicDataBlock.Data = device.Sector.DataBlock[i].Data; - childNodeViewModelFromChip.Children.First(x => x.DataBlockNumber == i).RequestRefresh(); + for (var i = 0; i < device.Sector.DataBlock.Count; i++) + { + childNodeViewModelFromChip.Children[i].DataBlockNumber = i; + childNodeViewModelTemp.Children[i].DataBlockNumber = i; - childNodeViewModelTemp.Children.First(x => x.DataBlockNumber == i).MifareClassicDataBlock.Data = device.Sector.DataBlock[i].Data; - childNodeViewModelTemp.Children.First(x => x.DataBlockNumber == i).RequestRefresh(); + childNodeViewModelFromChip.Children[i].MifareClassicDataBlock.DataBlockNumberChipBased = device.Sector.DataBlock.First(x => x.DataBlockNumberSectorBased == i).DataBlockNumberChipBased; - CurrentTaskErrorLevel = ERROR.NoError; - } - else - { - StatusText += string.Format("{0}: \tBut: unable to authenticate to sector: {1}, DataBlock: {2} using specified Keys\n", DateTime.Now, selectedClassicSectorCurrentAsInt, device.Sector.DataBlock[i - 1].DataBlockNumberChipBased); - } - } + if (device.Sector.DataBlock[i].IsAuthenticated) + { + StatusText += string.Format("{0}: \tSuccess for Blocknumber: {1} Data: {2}\n", DateTime.Now, device.Sector.DataBlock[i].DataBlockNumberChipBased, CustomConverter.HexToString(device.Sector.DataBlock[i].Data)); + childNodeViewModelFromChip.Children.First(x => x.DataBlockNumber == i).MifareClassicDataBlock.Data = device.Sector.DataBlock[i].Data; + childNodeViewModelFromChip.Children.First(x => x.DataBlockNumber == i).RequestRefresh(); - CurrentTaskErrorLevel = ERROR.NoError; + childNodeViewModelTemp.Children.First(x => x.DataBlockNumber == i).MifareClassicDataBlock.Data = device.Sector.DataBlock[i].Data; + childNodeViewModelTemp.Children.First(x => x.DataBlockNumber == i).RequestRefresh(); - } + CurrentTaskErrorLevel = ERROR.NoError; + } + else + { + StatusText += string.Format("{0}: \tBut: unable to authenticate to sector: {1}, DataBlock: {2} using specified Keys\n", DateTime.Now, selectedClassicSectorCurrentAsInt, device.Sector.DataBlock[i - 1].DataBlockNumberChipBased); + } + } - else - { - StatusText += string.Format("{0}: Unable to Authenticate to Sector: {1} using specified Keys\n", DateTime.Now, selectedClassicSectorCurrentAsInt); - CurrentTaskErrorLevel = ERROR.AuthenticationError; - return; - } - } + CurrentTaskErrorLevel = ERROR.NoError; - else - { - ChildNodeViewModelFromChip.Children.FirstOrDefault().MifareClassicMAD.MADApp = appNumberAsInt; - ChildNodeViewModelTemp.Children.FirstOrDefault().MifareClassicMAD.MADApp = appNumberAsInt; + } - if (device.ReadMifareClassicWithMAD(appNumberAsInt, - ClassicKeyAKeyCurrent, ClassicKeyBKeyCurrent, ClassicMADKeyAKeyCurrent, ClassicMADKeyBKeyCurrent, fileSizeAsInt, - madGPB, UseMAD, useMADAuth) == ERROR.NoError) - { - ChildNodeViewModelFromChip.Children.FirstOrDefault().MifareClassicMAD.Data = device.MifareClassicData; - ChildNodeViewModelTemp.Children.FirstOrDefault().MifareClassicMAD.Data = device.MifareClassicData; + else + { + StatusText += string.Format("{0}: Unable to Authenticate to Sector: {1} using specified Keys\n", DateTime.Now, selectedClassicSectorCurrentAsInt); + CurrentTaskErrorLevel = ERROR.AuthenticationError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } - ChildNodeViewModelTemp.Children.Single().RequestRefresh(); - ChildNodeViewModelFromChip.Children.Single().RequestRefresh(); + else + { + ChildNodeViewModelFromChip.Children.FirstOrDefault().MifareClassicMAD.MADApp = appNumberAsInt; + ChildNodeViewModelTemp.Children.FirstOrDefault().MifareClassicMAD.MADApp = appNumberAsInt; - StatusText = StatusText + string.Format("{0}: Successfully Read Data from MAD\n", DateTime.Now); + if (await device.ReadMifareClassicWithMAD(appNumberAsInt, + ClassicKeyAKeyCurrent, ClassicKeyBKeyCurrent, ClassicMADKeyAKeyCurrent, ClassicMADKeyBKeyCurrent, fileSizeAsInt, + madGPB, UseMAD, useMADAuth) == ERROR.NoError) + { + ChildNodeViewModelFromChip.Children.FirstOrDefault().MifareClassicMAD.Data = device.MifareClassicData; + ChildNodeViewModelTemp.Children.FirstOrDefault().MifareClassicMAD.Data = device.MifareClassicData; - CurrentTaskErrorLevel = ERROR.NoError; - } + ChildNodeViewModelTemp.Children.Single().RequestRefresh(); + ChildNodeViewModelFromChip.Children.Single().RequestRefresh(); - else - { - StatusText = StatusText + string.Format("{0}: Unable to Authenticate to MAD Sector using specified MAD Key(s)\n", DateTime.Now); + StatusText = StatusText + string.Format("{0}: Successfully Read Data from MAD\n", DateTime.Now); - CurrentTaskErrorLevel = ERROR.AuthenticationError; - return; - } - } + CurrentTaskErrorLevel = ERROR.NoError; + } + else + { + StatusText = StatusText + string.Format("{0}: Unable to Authenticate to MAD Sector using specified MAD Key(s)\n", DateTime.Now); - } + CurrentTaskErrorLevel = ERROR.AuthenticationError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } - OnPropertyChanged(nameof(ChildNodeViewModelTemp)); + } - return; - } - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - classicTask.ContinueWith((x) => + else { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + + OnPropertyChanged(nameof(ChildNodeViewModelTemp)); + } - classicTask.RunSynchronously(); + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; } + + await UpdateReaderStatusCommand.ExecuteAsync(false); } /// /// /// - public ICommand WriteDataCommand => new RelayCommand(OnNewWriteDataCommand); - private protected void OnNewWriteDataCommand() + public IAsyncRelayCommand WriteDataCommand => new AsyncRelayCommand(OnNewWriteDataCommand); + private protected async Task OnNewWriteDataCommand() { CurrentTaskErrorLevel = ERROR.Empty; - var classicTask = - new Task(() => - { - using (var device = ReaderDevice.Instance) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (!UseMAD) - { - if (device != null) - { - childNodeViewModelFromChip.SectorNumber = selectedClassicSectorCurrentAsInt; - childNodeViewModelTemp.SectorNumber = selectedClassicSectorCurrentAsInt; - - device.ReadChipPublic(); - - if (device.WriteMifareClassicSingleBlock(CustomConverter.GetChipBasedDataBlockNumber(selectedClassicSectorCurrentAsInt, (byte)SelectedDataBlockToReadWrite), - ClassicKeyAKeyCurrent, - ClassicKeyBKeyCurrent, - childNodeViewModelTemp.Children[(int)SelectedDataBlockToReadWrite].MifareClassicDataBlock.Data) == ERROR.NoError) - { - StatusText = StatusText + string.Format("{0}: \tSuccess for Blocknumber: {1} Data: {2}\n", - DateTime.Now, - childNodeViewModelFromChip.Children[(int)SelectedDataBlockToReadWrite].DataBlockNumber, - CustomConverter.HexToString(childNodeViewModelTemp.Children[(int)SelectedDataBlockToReadWrite].MifareClassicDataBlock.Data)); - CurrentTaskErrorLevel = ERROR.NoError; - } - else - { - StatusText = StatusText + string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxUnableToAuthenticate")); - CurrentTaskErrorLevel = ERROR.AuthenticationError; - } - } - else - { - StatusText = StatusText + string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxUnableToAuthenticate")); - CurrentTaskErrorLevel = ERROR.NotReadyError; - } - } - - else - { - ChildNodeViewModelFromChip.Children.FirstOrDefault().MifareClassicMAD.MADApp = appNumberAsInt; - ChildNodeViewModelTemp.Children.FirstOrDefault().MifareClassicMAD.MADApp = appNumberAsInt; - - if (device.WriteMifareClassicWithMAD(appNumberAsInt, selectedMADSectorAsInt, - ClassicKeyAKeyCurrent, ClassicKeyBKeyCurrent, - ClassicKeyAKeyTarget, ClassicKeyBKeyTarget, - ClassicMADKeyAKeyCurrent, ClassicMADKeyBKeyCurrent, - ClassicMADKeyAKeyTarget, ClassicMADKeyBKeyTarget, - ChildNodeViewModelTemp.Children.Single(x => x.MifareClassicMAD.MADApp == appNumberAsInt).MifareClassicMAD.Data, - madGPB, ChildNodeViewModelTemp.SectorModel.SAB, UseMadAuth, UseMAD) == ERROR.NoError) - { - StatusText = StatusText + string.Format("{0}: Wrote {1} bytes to MAD ID {2}\n", DateTime.Now, - ChildNodeViewModelTemp.Children.Single(x => x.MifareClassicMAD.MADApp == appNumberAsInt).MifareClassicMAD.Data.Length, - ChildNodeViewModelTemp.Children.Single(x => x.MifareClassicMAD.MADApp == appNumberAsInt).MifareClassicMAD.MADApp); - - CurrentTaskErrorLevel = ERROR.NoError; - } - - else - { - StatusText = StatusText + string.Format("{0}: Unable to Authenticate to MAD Sector using specified MAD Key(s)\n", DateTime.Now); - CurrentTaskErrorLevel = ERROR.AuthenticationError; - return; - } - } - } - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - classicTask.ContinueWith((x) => + using (var device = ReaderDevice.Instance) + { + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (!UseMAD) { - if (CurrentTaskErrorLevel == ERROR.NoError) + if (device != null) { - IsTaskCompletedSuccessfully = true; + await UpdateReaderStatusCommand.ExecuteAsync(true); + + childNodeViewModelFromChip.SectorNumber = selectedClassicSectorCurrentAsInt; + childNodeViewModelTemp.SectorNumber = selectedClassicSectorCurrentAsInt; + + await device.ReadChipPublic(); + + if (await device.WriteMifareClassicSingleBlock(CustomConverter.GetChipBasedDataBlockNumber(selectedClassicSectorCurrentAsInt, (byte)SelectedDataBlockToReadWrite), + ClassicKeyAKeyCurrent, + ClassicKeyBKeyCurrent, + childNodeViewModelTemp.Children[(int)SelectedDataBlockToReadWrite].MifareClassicDataBlock.Data) == ERROR.NoError) + { + StatusText = StatusText + string.Format("{0}: \tSuccess for Blocknumber: {1} Data: {2}\n", + DateTime.Now, + childNodeViewModelFromChip.Children[(int)SelectedDataBlockToReadWrite].DataBlockNumber, + CustomConverter.HexToString(childNodeViewModelTemp.Children[(int)SelectedDataBlockToReadWrite].MifareClassicDataBlock.Data)); + CurrentTaskErrorLevel = ERROR.NoError; + } + else + { + StatusText = StatusText + string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxUnableToAuthenticate")); + CurrentTaskErrorLevel = ERROR.AuthenticationError; + } } else { - IsTaskCompletedSuccessfully = false; + StatusText = StatusText + string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxUnableToAuthenticate")); + CurrentTaskErrorLevel = ERROR.NotReadyError; } - }); + } - classicTask.RunSynchronously(); + else + { + ChildNodeViewModelFromChip.Children.FirstOrDefault().MifareClassicMAD.MADApp = appNumberAsInt; + ChildNodeViewModelTemp.Children.FirstOrDefault().MifareClassicMAD.MADApp = appNumberAsInt; + + if (await device.WriteMifareClassicWithMAD(appNumberAsInt, selectedMADSectorAsInt, + ClassicKeyAKeyCurrent, ClassicKeyBKeyCurrent, + ClassicKeyAKeyTarget, ClassicKeyBKeyTarget, + ClassicMADKeyAKeyCurrent, ClassicMADKeyBKeyCurrent, + ClassicMADKeyAKeyTarget, ClassicMADKeyBKeyTarget, + ChildNodeViewModelTemp.Children.Single(x => x.MifareClassicMAD.MADApp == appNumberAsInt).MifareClassicMAD.Data, + madGPB, ChildNodeViewModelTemp.SectorModel.SAB, UseMadAuth, UseMAD) == ERROR.NoError) + { + StatusText = StatusText + string.Format("{0}: Wrote {1} bytes to MAD ID {2}\n", DateTime.Now, + ChildNodeViewModelTemp.Children.Single(x => x.MifareClassicMAD.MADApp == appNumberAsInt).MifareClassicMAD.Data.Length, + ChildNodeViewModelTemp.Children.Single(x => x.MifareClassicMAD.MADApp == appNumberAsInt).MifareClassicMAD.MADApp); + + CurrentTaskErrorLevel = ERROR.NoError; + } + + else + { + StatusText = StatusText + string.Format("{0}: Unable to Authenticate to MAD Sector using specified MAD Key(s)\n", DateTime.Now); + CurrentTaskErrorLevel = ERROR.AuthenticationError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } } - return; + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + await UpdateReaderStatusCommand.ExecuteAsync(false); } /// /// /// - public ICommand GetDataFromFileCommand => new RelayCommand(OnNewGetDataFromFileCommand); - private void OnNewGetDataFromFileCommand() + public IAsyncRelayCommand GetDataFromFileCommand => new AsyncRelayCommand(OnNewGetDataFromFileCommand); + private async Task OnNewGetDataFromFileCommand() { var dlg = new OpenFileDialogViewModel { @@ -1974,7 +1952,7 @@ private void OnNewGetDataFromFileCommand() } catch (Exception e) { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } } @@ -1986,6 +1964,19 @@ private void OnNewGetDataFromFileCommand() [XmlIgnore] public bool IsModal { get; private set; } + public IAsyncRelayCommand UpdateReaderStatusCommand => new AsyncRelayCommand(UpdateStatus); + private async Task UpdateStatus(bool isBusy) + { + if (OnUpdateStatus != null) + { + OnUpdateStatus(isBusy); + } + else + { + return; + } + } + public virtual void RequestClose() { if (OnCloseRequest != null) @@ -2001,7 +1992,6 @@ public virtual void RequestClose() public event EventHandler DialogClosing; public ICommand OKCommand => new RelayCommand(Ok); - protected virtual void Ok() { if (OnOk != null) @@ -2015,7 +2005,6 @@ protected virtual void Ok() } public ICommand CancelCommand => new RelayCommand(Cancel); - protected virtual void Cancel() { if (OnCancel != null) @@ -2029,7 +2018,6 @@ protected virtual void Cancel() } public ICommand AuthCommand => new RelayCommand(Auth); - protected virtual void Auth() { if (OnAuth != null) @@ -2042,6 +2030,9 @@ protected virtual void Auth() } } + [XmlIgnore] + public Action OnUpdateStatus { get; set; } + [XmlIgnore] public Action OnOk { get; set; } diff --git a/RFiDGear/ViewModel/TaskSetupViewModels/MifareDesfireSetupViewModel.cs b/RFiDGear/ViewModel/TaskSetupViewModels/MifareDesfireSetupViewModel.cs index 57c1b5c..7a8278e 100644 --- a/RFiDGear/ViewModel/TaskSetupViewModels/MifareDesfireSetupViewModel.cs +++ b/RFiDGear/ViewModel/TaskSetupViewModels/MifareDesfireSetupViewModel.cs @@ -11,19 +11,20 @@ using MefMvvm.SharedContracts; using MefMvvm.SharedContracts.ViewModel; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using RFiDGear.DataAccessLayer.Remote.FromIO; using RFiDGear.DataAccessLayer; using RFiDGear.Model; using RFiDGear.ViewModel; -using Log4CSharp; + using System; using System.ComponentModel.Composition; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; @@ -40,7 +41,7 @@ namespace RFiDGear.ViewModel public class MifareDesfireSetupViewModel : ObservableObject, IUserDialogViewModel, IGenericTaskModel { #region Fields - private static readonly string FacilityName = "RFiDGear"; + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private protected SettingsReaderWriter settings = new SettingsReaderWriter(); @@ -65,12 +66,12 @@ public MifareDesfireChipModel MifareDesfireChipModelToUse public MifareDesfireSetupViewModel() { accessRights = new DESFireAccessRights(); - chip = new MifareDesfireChipModel(string.Format("Task Description: {0}", SelectedTaskDescription), CARD_TYPE.DESFire); + chip = new MifareDesfireChipModel(string.Format("Task Description: {0}", SelectedTaskDescription), CARD_TYPE.DESFireEV1); app = new MifareDesfireAppModel(0); - childNodeViewModelFromChip = new RFiDChipChildLayerViewModel(app, null, CARD_TYPE.DESFire, new ObservableCollection(), true); - childNodeViewModelTemp = new RFiDChipChildLayerViewModel(app, null, CARD_TYPE.DESFire, new ObservableCollection(), true); + childNodeViewModelFromChip = new RFiDChipChildLayerViewModel(app, null, chip.CardType, new ObservableCollection(), true); + childNodeViewModelTemp = new RFiDChipChildLayerViewModel(app, null, chip.CardType, new ObservableCollection(), true); MifareDesfireKeys = CustomConverter.GenerateStringSequence(0, 16).ToArray(); MifareDesfireKeyCount = CustomConverter.GenerateStringSequence(1, 16).ToArray(); @@ -95,11 +96,11 @@ public MifareDesfireSetupViewModel(object _selectedSetupViewModel, ObservableCol { MefHelper.Instance.Container.ComposeParts(this); //Load Plugins - chip = new MifareDesfireChipModel(string.Format("Task Description: {0}", ""), CARD_TYPE.DESFire); + chip = new MifareDesfireChipModel(string.Format("Task Description: {0}", ""), CARD_TYPE.DESFireEV1); app = new MifareDesfireAppModel(0); - childNodeViewModelFromChip = new RFiDChipChildLayerViewModel(app, null, CARD_TYPE.DESFire, _dialogs, true); - childNodeViewModelTemp = new RFiDChipChildLayerViewModel(app, null, CARD_TYPE.DESFire, _dialogs, true); + childNodeViewModelFromChip = new RFiDChipChildLayerViewModel(app, null, chip.CardType, _dialogs, true); + childNodeViewModelTemp = new RFiDChipChildLayerViewModel(app, null, chip.CardType, _dialogs, true); MifareDesfireKeys = CustomConverter.GenerateStringSequence(0, 16).ToArray(); MifareDesfireKeyCount = CustomConverter.GenerateStringSequence(1, 16).ToArray(); @@ -202,7 +203,7 @@ public MifareDesfireSetupViewModel(object _selectedSetupViewModel, ObservableCol } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } #endregion @@ -734,7 +735,7 @@ public string DesfireMasterKeyCurrent { try { - desfireMasterKeyCurrent = value.ToUpper().Remove(32); + desfireMasterKeyCurrent = value.Length > 32 ? value.ToUpper().Remove(32) : value; } catch { @@ -785,7 +786,7 @@ public string DesfireMasterKeyTarget { try { - desfireMasterKeyTarget = value.ToUpper().Remove(32); + desfireMasterKeyTarget = value.Length > 32 ? value.ToUpper().Remove(32) : value; } catch { @@ -877,7 +878,7 @@ public string AppNumberNew { try { - appNumberNew = value.ToUpper().Remove(32); + appNumberNew = value.Length > 8 ? value.ToUpper().Remove(8) : value; } catch { @@ -1013,7 +1014,7 @@ public string DesfireAppKeyCurrent { try { - desfireAppKeyCurrent = value.ToUpper().Remove(32); + desfireAppKeyCurrent = value.Length > 32 ? value.ToUpper().Remove(32) : value; } catch { @@ -1050,7 +1051,7 @@ public string AppNumberCurrent { try { - appNumberCurrent = value.ToUpper().Remove(32); + appNumberCurrent = value.Length > 8 ? value.ToUpper().Remove(8) : value; } catch { @@ -1151,7 +1152,7 @@ public string DesfireAppKeyTarget { try { - desfireAppKeyTarget = value.ToUpper().Remove(32); + desfireAppKeyTarget = value.Length > 32 ? value.ToUpper().Remove(32) : value; } catch { @@ -1191,7 +1192,7 @@ public string AppNumberTarget { try { - appNumberTarget = value.ToUpper().Remove(32); + appNumberTarget = value.Length > 8 ? value.ToUpper().Remove(8) : value; } catch { @@ -1459,7 +1460,7 @@ public string DesfireReadKeyCurrent { try { - desfireReadKeyCurrent = value.ToUpper().Remove(32); + desfireReadKeyCurrent = value.Length > 32 ? value.ToUpper().Remove(32) : value; } catch { @@ -1518,7 +1519,7 @@ public string DesfireWriteKeyCurrent { try { - desfireWriteKeyCurrent = value.ToUpper().Remove(32); + desfireWriteKeyCurrent = value.Length > 32 ? value.ToUpper().Remove(32) : value; } catch { @@ -1601,57 +1602,67 @@ public DESFireKeyType SelectedDesfireWriteKeyEncryptionType #region Commands - public ICommand CommandDelegator => new RelayCommand((x) => OnNewCommandDelegatorCall(x)); - private void OnNewCommandDelegatorCall(TaskType_MifareDesfireTask desfireTaskType) + /// + /// + /// + public IAsyncRelayCommand SaveSettings => new AsyncRelayCommand(OnNewSaveSettingsCommand); + private async Task OnNewSaveSettingsCommand() + { + SettingsReaderWriter settings = new SettingsReaderWriter(); + await settings.SaveSettings(); + } + + public IAsyncRelayCommand CommandDelegator => new AsyncRelayCommand((x) => OnNewCommandDelegatorCall(x)); + private async Task OnNewCommandDelegatorCall(TaskType_MifareDesfireTask desfireTaskType) { switch (desfireTaskType) { case TaskType_MifareDesfireTask.AppExistCheck: - DoesAppExistCommand(null); + await DoesAppExistCommand(null); break; case TaskType_MifareDesfireTask.ApplicationKeyChangeover: - OnNewChangeAppKeyCommand(); + await OnNewChangeAppKeyCommand(); break; case TaskType_MifareDesfireTask.AuthenticateApplication: - OnNewAuthenticateToCardApplicationCommand(); + await OnNewAuthenticateToCardApplicationCommand(); break; case TaskType_MifareDesfireTask.CreateApplication: - OnNewCreateAppCommand(); + await OnNewCreateAppCommand(); break; case TaskType_MifareDesfireTask.CreateFile: - OnNewCreateFileCommand(); + await OnNewCreateFileCommand(); break; case TaskType_MifareDesfireTask.DeleteApplication: - OnNewDeleteSignleCardApplicationCommand(); + await OnNewDeleteSignleCardApplicationCommand(); break; case TaskType_MifareDesfireTask.DeleteFile: - OnNewDeleteFileCommand(); + await OnNewDeleteFileCommand(); break; case TaskType_MifareDesfireTask.FormatDesfireCard: - OnNewFormatDesfireCardCommand(); + await OnNewFormatDesfireCardCommand(); break; case TaskType_MifareDesfireTask.PICCMasterKeyChangeover: - OnNewChangeMasterCardKeyCommand(); + await OnNewChangeMasterCardKeyCommand(); break; case TaskType_MifareDesfireTask.ReadAppSettings: - ReadAppSettingsCommand(); + await ReadAppSettingsCommand(); break; case TaskType_MifareDesfireTask.ReadData: - OnNewReadDataCommand(); + await OnNewReadDataCommand(); break; case TaskType_MifareDesfireTask.WriteData: - OnNewWriteDataCommand(); + await OnNewWriteDataCommand(); break; default: @@ -1662,129 +1673,124 @@ private void OnNewCommandDelegatorCall(TaskType_MifareDesfireTask desfireTaskTyp /// /// return new RelayCommand((_device) => OnNewCreateAppCommand(_device)); /// - public ICommand CreateAppCommand => new RelayCommand(OnNewCreateAppCommand); - private void OnNewCreateAppCommand() + public IAsyncRelayCommand CreateAppCommand => new AsyncRelayCommand(OnNewCreateAppCommand); + private async Task OnNewCreateAppCommand() { CurrentTaskErrorLevel = ERROR.Empty; - var desfireTask = - new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) - { - var result = device.AuthToMifareDesfireApplication( - DesfireMasterKeyCurrent, - SelectedDesfireMasterKeyEncryptionTypeCurrent, - 0); - - if (IsValidAppNumberNew != false && result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Authenticated to App 0\n", DateTime.Now); - - DESFireKeySettings keySettings; - keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; - - keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; - keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; - keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; - keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; - - result = device.CreateMifareDesfireApplication( - DesfireMasterKeyCurrent, - keySettings, - SelectedDesfireMasterKeyEncryptionTypeCurrent, - SelectedDesfireAppKeyEncryptionTypeCreateNewApp, - selectedDesfireAppMaxNumberOfKeysAsInt, - AppNumberNewAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Created AppID {1}\n", DateTime.Now, AppNumberNewAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to Create App: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - else - { - StatusText += string.Format("{0}: Authentication to PICC failed. Try without Authentication...\n", DateTime.Now); - - DESFireKeySettings keySettings; - keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; - - keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; - keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; - keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; - keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; - - result = device.CreateMifareDesfireApplication( - DesfireMasterKeyCurrent, - keySettings, - SelectedDesfireMasterKeyEncryptionTypeCurrent, - SelectedDesfireAppKeyEncryptionTypeCreateNewApp, - selectedDesfireAppMaxNumberOfKeysAsInt, - AppNumberNewAsInt, false); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Created AppID {1}\n", DateTime.Now, AppNumberNewAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to create App: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - } - } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } - } - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); + using (var device = ReaderDevice.Instance) + { + if (device != null) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); + + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) + { + var result = await device.AuthToMifareDesfireApplication( + DesfireMasterKeyCurrent, + SelectedDesfireMasterKeyEncryptionTypeCurrent, + 0); + + if (IsValidAppNumberNew != false && result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Authenticated to App 0\n", DateTime.Now); + + DESFireKeySettings keySettings; + keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; + + keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; + keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; + keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; + keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; + + result = await device.CreateMifareDesfireApplication( + DesfireMasterKeyCurrent, + keySettings, + SelectedDesfireMasterKeyEncryptionTypeCurrent, + SelectedDesfireAppKeyEncryptionTypeCreateNewApp, + selectedDesfireAppMaxNumberOfKeysAsInt, + AppNumberNewAsInt); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Created AppID {1}\n", DateTime.Now, AppNumberNewAsInt); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: Unable to Create App: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + else + { + StatusText += string.Format("{0}: Authentication to PICC failed. Try without Authentication...\n", DateTime.Now); + + DESFireKeySettings keySettings; + keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; + + keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; + keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; + keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; + keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; + + result = await device.CreateMifareDesfireApplication( + DesfireMasterKeyCurrent, + keySettings, + SelectedDesfireMasterKeyEncryptionTypeCurrent, + SelectedDesfireAppKeyEncryptionTypeCreateNewApp, + selectedDesfireAppMaxNumberOfKeysAsInt, + AppNumberNewAsInt, false); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Created AppID {1}\n", DateTime.Now, AppNumberNewAsInt); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: Unable to create App: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + } + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } } + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } /// /// return new RelayCommand((_device) => OnNewCreateAppCommand(_device)); /// - public ICommand CreateFileCommand => new RelayCommand(OnNewCreateFileCommand); - private void OnNewCreateFileCommand() + public IAsyncRelayCommand CreateFileCommand => new AsyncRelayCommand(OnNewCreateFileCommand); + private async Task OnNewCreateFileCommand() { CurrentTaskErrorLevel = ERROR.Empty; @@ -1793,200 +1799,188 @@ private void OnNewCreateFileCommand() accessRights.writeAccess = SelectedDesfireFileAccessRightWrite; accessRights.readAndWriteAccess = SelectedDesfireFileAccessRightReadWrite; - var desfireTask = - new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR && IsValidAppNumberNew != false) - { - var result = device.AuthToMifareDesfireApplication( - DesfireAppKeyCurrent, - SelectedDesfireAppKeyEncryptionTypeCurrent, - selectedDesfireAppKeyNumberCurrentAsInt, AppNumberCurrentAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); - - result = device.CreateMifareDesfireFile( - DesfireAppKeyCurrent, - SelectedDesfireAppKeyEncryptionTypeCurrent, - SelectedDesfireFileType, - accessRights, - SelectedDesfireFileCryptoMode, - AppNumberCurrentAsInt, - FileNumberCurrentAsInt, - FileSizeCurrentAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Created FileNo: {1} with Size: {2} in AppID: {3}\n", DateTime.Now, FileNumberCurrentAsInt, FileSizeCurrentAsInt, AppNumberNewAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to Create File: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - - else - { - StatusText += string.Format("{0}: Unable to Authenticate to App {1}; Try to Continue Anyway...\n", DateTime.Now, AppNumberCurrentAsInt); - - result = device.CreateMifareDesfireFile( - DesfireAppKeyCurrent, - SelectedDesfireAppKeyEncryptionTypeCurrent, - SelectedDesfireFileType, - accessRights, - SelectedDesfireFileCryptoMode, - AppNumberCurrentAsInt, - FileNumberCurrentAsInt, - FileSizeCurrentAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Created FileNo: {1} with Size: {2} in AppID: {3}\n", DateTime.Now, FileNumberCurrentAsInt, FileSizeCurrentAsInt, AppNumberNewAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to Create File: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - } - } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } - } - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); + using (var device = ReaderDevice.Instance) + { + if (device != null) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); + + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR && IsValidAppNumberNew != false) + { + var result = await device.AuthToMifareDesfireApplication( + DesfireAppKeyCurrent, + SelectedDesfireAppKeyEncryptionTypeCurrent, + selectedDesfireAppKeyNumberCurrentAsInt, AppNumberCurrentAsInt); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); + + result = await device.CreateMifareDesfireFile( + DesfireAppKeyCurrent, + SelectedDesfireAppKeyEncryptionTypeCurrent, + SelectedDesfireFileType, + accessRights, + SelectedDesfireFileCryptoMode, + AppNumberCurrentAsInt, + FileNumberCurrentAsInt, + FileSizeCurrentAsInt); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Created FileNo: {1} with Size: {2} in AppID: {3}\n", DateTime.Now, FileNumberCurrentAsInt, FileSizeCurrentAsInt, AppNumberNewAsInt); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: Unable to Create File: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + + else + { + StatusText += string.Format("{0}: Unable to Authenticate to App {1}; Try to Continue Anyway...\n", DateTime.Now, AppNumberCurrentAsInt); + + result = await device.CreateMifareDesfireFile( + DesfireAppKeyCurrent, + SelectedDesfireAppKeyEncryptionTypeCurrent, + SelectedDesfireFileType, + accessRights, + SelectedDesfireFileCryptoMode, + AppNumberCurrentAsInt, + FileNumberCurrentAsInt, + FileSizeCurrentAsInt); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Created FileNo: {1} with Size: {2} in AppID: {3}\n", DateTime.Now, FileNumberCurrentAsInt, FileSizeCurrentAsInt, AppNumberNewAsInt); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: Unable to Create File: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + } + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } } + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } /// /// /// - public ICommand ReadDataCommand => new RelayCommand(OnNewReadDataCommand); - private void OnNewReadDataCommand() + public IAsyncRelayCommand ReadDataCommand => new AsyncRelayCommand(OnNewReadDataCommand); + private async Task OnNewReadDataCommand() { CurrentTaskErrorLevel = ERROR.Empty; - var desfireTask = - new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) - { - var result = device.AuthToMifareDesfireApplication( - DesfireReadKeyCurrent, - SelectedDesfireReadKeyEncryptionType, - selectedDesfireReadKeyNumberAsInt, AppNumberCurrentAsInt); - - - if (IsValidAppNumberNew != false && result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); - - result = device.ReadMiFareDESFireChipFile(DesfireAppKeyCurrent, SelectedDesfireAppKeyEncryptionTypeCurrent, - DesfireReadKeyCurrent, SelectedDesfireReadKeyEncryptionType, selectedDesfireReadKeyNumberAsInt, - DesfireWriteKeyCurrent, SelectedDesfireWriteKeyEncryptionType, selectedDesfireWriteKeyNumberAsInt, - EncryptionMode.CM_ENCRYPT, FileNumberCurrentAsInt, AppNumberCurrentAsInt, FileSizeCurrentAsInt); - - if (result == ERROR.NoError) - { - FileSizeCurrent = device.MifareDESFireData.Length.ToString(CultureInfo.CurrentCulture); - - StatusText += string.Format("{0}: Successfully Read {2} Bytes Data from FileNo: {1} in AppID: {3}\n", DateTime.Now, FileNumberCurrentAsInt, FileSizeCurrentAsInt, AppNumberNewAsInt); - - childNodeViewModelFromChip.Children.Single(x => x.DesfireFile != null).DesfireFile = new MifareDesfireFileModel(device.MifareDESFireData, (byte)FileNumberCurrentAsInt); - - childNodeViewModelTemp.Children.Single(x => x.DesfireFile != null).DesfireFile = new MifareDesfireFileModel(device.MifareDESFireData, (byte)FileNumberCurrentAsInt); - - CurrentTaskErrorLevel = result; - - OnPropertyChanged(nameof(ChildNodeViewModelTemp)); - OnPropertyChanged(nameof(ChildNodeViewModelFromChip)); - - return; - } - else - { - StatusText += string.Format("{0}: Unable to Read File with FileID: {1}: {2}", DateTime.Now, FileNumberCurrentAsInt, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - else - { - StatusText += string.Format("{0}: Unable to Read File: {1}", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } - } - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); + using (var device = ReaderDevice.Instance) + { + if (device != null) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); + + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) + { + var result = await device.AuthToMifareDesfireApplication( + DesfireReadKeyCurrent, + SelectedDesfireReadKeyEncryptionType, + selectedDesfireReadKeyNumberAsInt, AppNumberCurrentAsInt); + + + if (IsValidAppNumberNew != false && result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); + + result = await device.ReadMiFareDESFireChipFile(DesfireAppKeyCurrent, SelectedDesfireAppKeyEncryptionTypeCurrent, + DesfireReadKeyCurrent, SelectedDesfireReadKeyEncryptionType, selectedDesfireReadKeyNumberAsInt, + DesfireWriteKeyCurrent, SelectedDesfireWriteKeyEncryptionType, selectedDesfireWriteKeyNumberAsInt, + EncryptionMode.CM_ENCRYPT, FileNumberCurrentAsInt, AppNumberCurrentAsInt, FileSizeCurrentAsInt); + + if (result == ERROR.NoError) + { + FileSizeCurrent = device.MifareDESFireData.Length.ToString(CultureInfo.CurrentCulture); + + StatusText += string.Format("{0}: Successfully Read {2} Bytes Data from FileNo: {1} in AppID: {3}\n", DateTime.Now, FileNumberCurrentAsInt, FileSizeCurrentAsInt, AppNumberNewAsInt); + + childNodeViewModelFromChip.Children.Single(x => x.DesfireFile != null).DesfireFile = new MifareDesfireFileModel(device.MifareDESFireData, (byte)FileNumberCurrentAsInt); + + childNodeViewModelTemp.Children.Single(x => x.DesfireFile != null).DesfireFile = new MifareDesfireFileModel(device.MifareDESFireData, (byte)FileNumberCurrentAsInt); + + CurrentTaskErrorLevel = result; + + OnPropertyChanged(nameof(ChildNodeViewModelTemp)); + OnPropertyChanged(nameof(ChildNodeViewModelFromChip)); + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: Unable to Read File with FileID: {1}: {2}", DateTime.Now, FileNumberCurrentAsInt, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + else + { + StatusText += string.Format("{0}: Unable to Read File: {1}", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } } + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } @@ -2018,7 +2012,7 @@ private void OnNewGetDataFromFileCommand() } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } } @@ -2026,740 +2020,697 @@ private void OnNewGetDataFromFileCommand() /// /// /// - public ICommand WriteDataCommand => new RelayCommand(OnNewWriteDataCommand); - private void OnNewWriteDataCommand() + public IAsyncRelayCommand WriteDataCommand => new AsyncRelayCommand(OnNewWriteDataCommand); + private async Task OnNewWriteDataCommand() { CurrentTaskErrorLevel = ERROR.Empty; - var desfireTask = - new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) - { - - var result = device.AuthToMifareDesfireApplication( - DesfireWriteKeyCurrent, - SelectedDesfireWriteKeyEncryptionType, - selectedDesfireWriteKeyNumberAsInt, AppNumberCurrentAsInt); - - if (IsValidAppNumberNew != false && result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); - - result = device.WriteMiFareDESFireChipFile(DesfireAppKeyCurrent, SelectedDesfireAppKeyEncryptionTypeCurrent, - DesfireAppKeyCurrent, SelectedDesfireAppKeyEncryptionTypeCurrent, - DesfireReadKeyCurrent, SelectedDesfireReadKeyEncryptionType, selectedDesfireReadKeyNumberAsInt, - DesfireWriteKeyCurrent, SelectedDesfireWriteKeyEncryptionType, selectedDesfireWriteKeyNumberAsInt, - EncryptionMode.CM_ENCRYPT, FileNumberCurrentAsInt, AppNumberCurrentAsInt, childNodeViewModelTemp.Children.Single(x => x.DesfireFile != null).DesfireFile.Data); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Created FileNo: {1} with Size: {2} in AppID: {3}\n", DateTime.Now, FileNumberCurrentAsInt, FileSizeCurrentAsInt, AppNumberNewAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to Write Data: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - else - { - StatusText += string.Format("{0}: Unable to Write Data: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } - } - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); - } - - - return; - } - - /// - /// - /// - public ICommand ChangeAppKeyCommand => new RelayCommand(OnNewChangeAppKeyCommand); - private void OnNewChangeAppKeyCommand() - { - CurrentTaskErrorLevel = ERROR.Empty; + using (var device = ReaderDevice.Instance) + { + if (device != null) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - var desfireTask = new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) - { - var result = device.AuthToMifareDesfireApplication( - DesfireAppKeyCurrent, - SelectedDesfireAppKeyEncryptionTypeCurrent, - selectedDesfireAppKeyNumberCurrentAsInt, - AppNumberCurrentAsInt); - - if (IsValidAppNumberCurrent != false && - IsValidAppNumberTarget != false && - IsValidDesfireAppKeyTarget != false && - result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Authenticated to AppID {1}\n", DateTime.Now, AppNumberCurrentAsInt); - - var keySettings = DESFireKeySettings.KS_DEFAULT; - keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; - - keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; - keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; - keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; - keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; - - result = device.ChangeMifareDesfireApplicationKey(DesfireAppKeyCurrent, - selectedDesfireAppKeyNumberCurrentAsInt, - SelectedDesfireAppKeyEncryptionTypeCurrent, - DesfireAppKeyTarget, - selectedDesfireAppKeyNumberTargetAsInt, - selectedDesfireAppKeyVersionTargetAsInt, - SelectedDesfireAppKeyEncryptionTypeTarget, - AppNumberCurrentAsInt, AppNumberTargetAsInt, keySettings, keyVersionCurrentAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Changed Key {1} of AppID {2}\n", DateTime.Now, selectedDesfireAppKeyNumberTargetAsInt, AppNumberTargetAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to Change Key {1} of AppID {2}: {3}\n", DateTime.Now, selectedDesfireAppKeyNumberCurrentAsInt, AppNumberTargetAsInt, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - else - { - StatusText += string.Format("{0}: Unable to Change Key {1} of AppID {2}: {3}\n", DateTime.Now, selectedDesfireAppKeyNumberCurrentAsInt, AppNumberTargetAsInt, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } - } - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); - } + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) + { + var result = await device.AuthToMifareDesfireApplication( + DesfireWriteKeyCurrent, + SelectedDesfireWriteKeyEncryptionType, + selectedDesfireWriteKeyNumberAsInt, AppNumberCurrentAsInt); - return; - } + if (IsValidAppNumberNew != false && result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); - /// - /// - /// - public ICommand DeleteSignleCardApplicationCommand => new RelayCommand(OnNewDeleteSignleCardApplicationCommand); - private void OnNewDeleteSignleCardApplicationCommand() - { - CurrentTaskErrorLevel = ERROR.Empty; + result = await device.WriteMiFareDESFireChipFile(DesfireAppKeyCurrent, SelectedDesfireAppKeyEncryptionTypeCurrent, + DesfireAppKeyCurrent, SelectedDesfireAppKeyEncryptionTypeCurrent, + DesfireReadKeyCurrent, SelectedDesfireReadKeyEncryptionType, selectedDesfireReadKeyNumberAsInt, + DesfireWriteKeyCurrent, SelectedDesfireWriteKeyEncryptionType, selectedDesfireWriteKeyNumberAsInt, + EncryptionMode.CM_ENCRYPT, FileNumberCurrentAsInt, AppNumberCurrentAsInt, childNodeViewModelTemp.Children.Single(x => x.DesfireFile != null).DesfireFile.Data); - var desfireTask = new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) - { - var result = device.AuthToMifareDesfireApplication( - DesfireMasterKeyCurrent, - SelectedDesfireMasterKeyEncryptionTypeCurrent, - 0); - - if (IsValidAppNumberCurrent != false && result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Authenticated to PICC Master App 0\n", DateTime.Now); - - result = device.DeleteMifareDesfireApplication( - DesfireMasterKeyCurrent, - SelectedDesfireMasterKeyEncryptionTypeCurrent, - AppNumberNewAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Deleted AppID {1}\n", DateTime.Now, AppNumberNewAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to Remove AppID {1}: {2}\n", DateTime.Now, AppNumberNewAsInt, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - - else - { - StatusText += string.Format("{0}: Authentication to PICC failed. Try without Authentication...\n", DateTime.Now); - - result = device.DeleteMifareDesfireApplication( - DesfireMasterKeyCurrent, - SelectedDesfireMasterKeyEncryptionTypeCurrent, - AppNumberNewAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully deleted AppID {1}\n", DateTime.Now, AppNumberNewAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to deleted App: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - } - } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } - } - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Created FileNo: {1} with Size: {2} in AppID: {3}\n", DateTime.Now, FileNumberCurrentAsInt, FileSizeCurrentAsInt, AppNumberNewAsInt); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: Unable to Write Data: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + else + { + StatusText += string.Format("{0}: Unable to Write Data: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } } - - return; - } - - /// - /// - /// - public ICommand DeleteFileCommand => new RelayCommand(OnNewDeleteFileCommand); - private void OnNewDeleteFileCommand() - { - CurrentTaskErrorLevel = ERROR.Empty; - - var desfireTask = new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) - { - var result = device.AuthToMifareDesfireApplication( - DesfireAppKeyCurrent, - SelectedDesfireAppKeyEncryptionTypeCurrent, - selectedDesfireAppKeyNumberCurrentAsInt, AppNumberCurrentAsInt); - - if (IsValidAppNumberCurrent != false && result == ERROR.NoError) - { - - StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); - - result = device.DeleteMifareDesfireFile( - DesfireAppKeyCurrent, - SelectedDesfireAppKeyEncryptionTypeCurrent, - AppNumberCurrentAsInt, FileNumberCurrentAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Deleted File {1}\n", DateTime.Now, FileNumberCurrentAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to Remove FileID {1}: {2}\n", DateTime.Now, FileNumberCurrentAsInt, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - else - { - StatusText += string.Format("{0}: Unable to Authenticate to App {1}; Try to Continue Anyway...\n", DateTime.Now, AppNumberCurrentAsInt); - - result = device.DeleteMifareDesfireFile( - DesfireAppKeyCurrent, - SelectedDesfireAppKeyEncryptionTypeCurrent, - AppNumberNewAsInt, FileNumberCurrentAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Deleted File {1}\n", DateTime.Now, FileNumberCurrentAsInt); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to Remove AppID {1}: {2}\n", DateTime.Now, AppNumberNewAsInt, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - } - } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } - } - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; } - - - return; - } - - /// - /// public ICommand FormatDesfireCardCommand { get { return new RelayCommand((_device) => OnNewFormatDesfireCardCommand(_device)); }} - /// - public ICommand FormatDesfireCardCommand => new RelayCommand(OnNewFormatDesfireCardCommand); - private void OnNewFormatDesfireCardCommand() - { - CurrentTaskErrorLevel = ERROR.Empty; - - var desfireTask = new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) - { - var result = device.AuthToMifareDesfireApplication( - DesfireMasterKeyCurrent, - SelectedDesfireMasterKeyEncryptionTypeCurrent, - 0); - - if (IsValidAppNumberCurrent != false && result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Authenticated to PICC Master App 0\n", DateTime.Now); - - result = device.GetMiFareDESFireChipAppIDs( - DesfireMasterKeyCurrent, - SelectedDesfireMasterKeyEncryptionTypeCurrent); - - if (result == ERROR.NoError) - { - if (device?.DesfireChip?.AppIDs != null) - { - foreach (var appID in device.DesfireChip.AppIDs) - { - StatusText += string.Format("{0}: FoundAppID {1}\n", DateTime.Now, appID); - } - } - - result = device.FormatDesfireCard(DesfireMasterKeyCurrent, SelectedDesfireMasterKeyEncryptionTypeCurrent); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Formatted Card\n", DateTime.Now); - CurrentTaskErrorLevel = result; - return; - } - - else - { - StatusText += string.Format("{0}: Unable to Format Card: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - - else - { - StatusText += string.Format("{0}: Unable to get Directory Listing, Try to Continue anyway...\n", DateTime.Now); - - result = device.FormatDesfireCard(DesfireMasterKeyCurrent, SelectedDesfireMasterKeyEncryptionTypeCurrent); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Formatted Card\n", DateTime.Now); - CurrentTaskErrorLevel = result; - return; - } - - else - { - StatusText += string.Format("{0}: Unable to Format Card: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - } - else - { - StatusText += string.Format("{0}: Unable to Format Card: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - } - else - { - CurrentTaskErrorLevel = ERROR.NotReadyError; - return; - } - } - return; - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); + else + { + IsTaskCompletedSuccessfully = false; } - + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } /// /// /// - public ICommand AuthenticateToCardApplicationCommand => new RelayCommand(OnNewAuthenticateToCardApplicationCommand); - private void OnNewAuthenticateToCardApplicationCommand() + public IAsyncRelayCommand ChangeAppKeyCommand => new AsyncRelayCommand(OnNewChangeAppKeyCommand); + private async Task OnNewChangeAppKeyCommand() { CurrentTaskErrorLevel = ERROR.Empty; - if (SelectedTaskType == TaskType_MifareDesfireTask.ReadAppSettings) + using (var device = ReaderDevice.Instance) { - return; - } + if (device != null) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); - else if (SelectedTaskType == TaskType_MifareDesfireTask.AppExistCheck) - { - DoesAppExistCommand(new MifareDesfireChipModel()); - return; - } + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - var desfireTask = new Task(() => - { - using (var device = ReaderDevice.Instance) - { - if (device != null) + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) + var result = await device.AuthToMifareDesfireApplication( + DesfireAppKeyCurrent, + SelectedDesfireAppKeyEncryptionTypeCurrent, + selectedDesfireAppKeyNumberCurrentAsInt, + AppNumberCurrentAsInt); + + if (IsValidAppNumberCurrent != false && + IsValidAppNumberTarget != false && + IsValidDesfireAppKeyTarget != false && + result == ERROR.NoError) { - var result = device.AuthToMifareDesfireApplication( - DesfireAppKeyCurrent, - SelectedDesfireAppKeyEncryptionTypeCurrent, - selectedDesfireAppKeyNumberCurrentAsInt, - AppNumberCurrentAsInt); + StatusText += string.Format("{0}: Successfully Authenticated to AppID {1}\n", DateTime.Now, AppNumberCurrentAsInt); + + var keySettings = DESFireKeySettings.KS_DEFAULT; + keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; + + keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; + keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; + keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; + keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; - if (IsValidAppNumberCurrent != false && result == ERROR.NoError) + result = await device.ChangeMifareDesfireApplicationKey(DesfireAppKeyCurrent, + selectedDesfireAppKeyNumberCurrentAsInt, + SelectedDesfireAppKeyEncryptionTypeCurrent, + DesfireAppKeyTarget, + selectedDesfireAppKeyNumberTargetAsInt, + selectedDesfireAppKeyVersionTargetAsInt, + SelectedDesfireAppKeyEncryptionTypeTarget, + AppNumberCurrentAsInt, AppNumberTargetAsInt, keySettings, keyVersionCurrentAsInt); + + if (result == ERROR.NoError) { - StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); + StatusText += string.Format("{0}: Successfully Changed Key {1} of AppID {2}\n", DateTime.Now, selectedDesfireAppKeyNumberTargetAsInt, AppNumberTargetAsInt); CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; } else { - StatusText += string.Format("{0}: Unable to Authenticate: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + StatusText += string.Format("{0}: Unable to Change Key {1} of AppID {2}: {3}\n", DateTime.Now, selectedDesfireAppKeyNumberCurrentAsInt, AppNumberTargetAsInt, result.ToString(CultureInfo.CurrentCulture)); CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; } - + } + else + { + StatusText += string.Format("{0}: Unable to Change Key {1} of AppID {2}: {3}\n", DateTime.Now, selectedDesfireAppKeyNumberCurrentAsInt, AppNumberTargetAsInt, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; } } } - return; - }); - - if (CurrentTaskErrorLevel == ERROR.Empty) - { - desfireTask.ContinueWith((x) => + else { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } - desfireTask.RunSynchronously(); + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; } + else + { + IsTaskCompletedSuccessfully = false; + } + + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } /// /// /// - public ICommand ChangeMasterCardKeyCommand => new RelayCommand(OnNewChangeMasterCardKeyCommand); - private void OnNewChangeMasterCardKeyCommand() + public IAsyncRelayCommand DeleteSignleCardApplicationCommand => new AsyncRelayCommand(OnNewDeleteSignleCardApplicationCommand); + private async Task OnNewDeleteSignleCardApplicationCommand() { CurrentTaskErrorLevel = ERROR.Empty; - var desfireTask = new Task( - () => + using (var device = ReaderDevice.Instance) + { + if (device != null) { - using (var device = ReaderDevice.Instance) + await UpdateReaderStatusCommand.ExecuteAsync(true); + + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) { - if (device != null) + var result = await device.AuthToMifareDesfireApplication( + DesfireMasterKeyCurrent, + SelectedDesfireMasterKeyEncryptionTypeCurrent, + 0); + + if (IsValidAppNumberCurrent != false && result == ERROR.NoError) { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + StatusText += string.Format("{0}: Successfully Authenticated to PICC Master App 0\n", DateTime.Now); - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireMasterKeyCurrent) == KEY_ERROR.NO_ERROR) + result = await device.DeleteMifareDesfireApplication( + DesfireMasterKeyCurrent, + SelectedDesfireMasterKeyEncryptionTypeCurrent, + (uint)AppNumberNewAsInt); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Deleted AppID {1}\n", DateTime.Now, AppNumberNewAsInt); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else { - DESFireKeySettings keySettings; - keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; + StatusText += string.Format("{0}: Unable to Remove AppID {1}: {2}\n", DateTime.Now, AppNumberNewAsInt, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } - keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; - keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; - keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; - keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; + else + { + StatusText += string.Format("{0}: Authentication to PICC failed. Try without Authentication...\n", DateTime.Now); - var result = device.AuthToMifareDesfireApplication( - CustomConverter.DesfireKeyToCheck, - SelectedDesfireMasterKeyEncryptionTypeCurrent, - 0); + result = await device.DeleteMifareDesfireApplication( + DesfireMasterKeyCurrent, + SelectedDesfireMasterKeyEncryptionTypeCurrent, + (uint)AppNumberNewAsInt); - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Successfully Authenticated to App 0\n", DateTime.Now); + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully deleted AppID {1}\n", DateTime.Now, AppNumberNewAsInt); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: Unable to deleted App: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + } + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } - if (IsValidDesfireMasterKeyCurrent != false && - IsValidDesfireMasterKeyTarget != false) - { - result = device.ChangeMifareDesfireApplicationKey( - DesfireMasterKeyCurrent, - 0, - SelectedDesfireMasterKeyEncryptionTypeCurrent, - DesfireMasterKeyTarget, - 0, - 0, - SelectedDesfireMasterKeyEncryptionTypeTarget, 0, 0, keySettings, keyVersionCurrentAsInt); - - if (result == ERROR.NoError) - { - StatusText += string.Format("{0}: Keychange Successfull\n", DateTime.Now); - CurrentTaskErrorLevel = result; - return; - } - else - { - StatusText += string.Format("{0}: Unable to Change Key: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; - return; - } - } - else + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + + /// + /// + /// + public IAsyncRelayCommand DeleteFileCommand => new AsyncRelayCommand(OnNewDeleteFileCommand); + private async Task OnNewDeleteFileCommand() + { + CurrentTaskErrorLevel = ERROR.Empty; + + using (var device = ReaderDevice.Instance) + { + if (device != null) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); + + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) + { + var result = await device.AuthToMifareDesfireApplication( + DesfireAppKeyCurrent, + SelectedDesfireAppKeyEncryptionTypeCurrent, + selectedDesfireAppKeyNumberCurrentAsInt, AppNumberCurrentAsInt); + + if (IsValidAppNumberCurrent != false && result == ERROR.NoError) + { + + StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); + + result = await device.DeleteMifareDesfireFile( + DesfireAppKeyCurrent, + SelectedDesfireAppKeyEncryptionTypeCurrent, + AppNumberCurrentAsInt, FileNumberCurrentAsInt); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Deleted File {1}\n", DateTime.Now, FileNumberCurrentAsInt); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: Unable to Remove FileID {1}: {2}\n", DateTime.Now, FileNumberCurrentAsInt, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + else + { + StatusText += string.Format("{0}: Unable to Authenticate to App {1}; Try to Continue Anyway...\n", DateTime.Now, AppNumberCurrentAsInt); + + result = await device.DeleteMifareDesfireFile( + DesfireAppKeyCurrent, + SelectedDesfireAppKeyEncryptionTypeCurrent, + AppNumberNewAsInt, FileNumberCurrentAsInt); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Deleted File {1}\n", DateTime.Now, FileNumberCurrentAsInt); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: Unable to Remove AppID {1}: {2}\n", DateTime.Now, AppNumberNewAsInt, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + } + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + + /// + /// public ICommand FormatDesfireCardCommand { get { return new RelayCommand((_device) => OnNewFormatDesfireCardCommand(_device)); }} + /// + public IAsyncRelayCommand FormatDesfireCardCommand => new AsyncRelayCommand(OnNewFormatDesfireCardCommand); + private async Task OnNewFormatDesfireCardCommand() + { + CurrentTaskErrorLevel = ERROR.Empty; + + using (var device = ReaderDevice.Instance) + { + if (device != null) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); + + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) + { + var result = await device.AuthToMifareDesfireApplication( + DesfireMasterKeyCurrent, + SelectedDesfireMasterKeyEncryptionTypeCurrent, + 0); + + if (IsValidAppNumberCurrent != false && result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Authenticated to PICC Master App 0\n", DateTime.Now); + + result = await device.GetMiFareDESFireChipAppIDs( + DesfireMasterKeyCurrent, + SelectedDesfireMasterKeyEncryptionTypeCurrent); + + if (result == ERROR.NoError) + { + if (device?.DesfireChip?.AppIDs != null) + { + foreach (var appID in device.DesfireChip.AppIDs) { - StatusText += string.Format("{0}: Key Error: Wrong Format\n", DateTime.Now); - CurrentTaskErrorLevel = ERROR.AuthenticationError; - return; + StatusText += string.Format("{0}: FoundAppID {1}\n", DateTime.Now, appID); } } + + result = await device.FormatDesfireCard(DesfireMasterKeyCurrent, SelectedDesfireMasterKeyEncryptionTypeCurrent); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Formatted Card\n", DateTime.Now); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + + else + { + StatusText += string.Format("{0}: Unable to Format Card: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + + else + { + StatusText += string.Format("{0}: Unable to get Directory Listing, Try to Continue anyway...\n", DateTime.Now); + + result = await device.FormatDesfireCard(DesfireMasterKeyCurrent, SelectedDesfireMasterKeyEncryptionTypeCurrent); + + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Formatted Card\n", DateTime.Now); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else { - StatusText += string.Format("{0}: {1}: {2}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxUnableToAuthenticate"), result.ToString(CultureInfo.CurrentCulture)); + StatusText += string.Format("{0}: Unable to Format Card: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } } } else { - CurrentTaskErrorLevel = ERROR.NotReadyError; + StatusText += string.Format("{0}: Unable to Format Card: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } } - }); + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } - if (CurrentTaskErrorLevel == ERROR.Empty) + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); + IsTaskCompletedSuccessfully = false; + } + + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + + /// + /// + /// + public IAsyncRelayCommand AuthenticateToCardApplicationCommand => new AsyncRelayCommand(OnNewAuthenticateToCardApplicationCommand); + private async Task OnNewAuthenticateToCardApplicationCommand() + { + CurrentTaskErrorLevel = ERROR.Empty; + + if (SelectedTaskType == TaskType_MifareDesfireTask.ReadAppSettings) + { + return; + } + + else if (SelectedTaskType == TaskType_MifareDesfireTask.AppExistCheck) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); + await DoesAppExistCommand(new MifareDesfireChipModel()); + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + + using (var device = ReaderDevice.Instance) + { + if (device != null) + { + await UpdateReaderStatusCommand.ExecuteAsync(true); + + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) + { + var result = await device.AuthToMifareDesfireApplication( + DesfireAppKeyCurrent, + SelectedDesfireAppKeyEncryptionTypeCurrent, + selectedDesfireAppKeyNumberCurrentAsInt, + AppNumberCurrentAsInt); + + if (IsValidAppNumberCurrent != false && result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Authenticated to App {1}\n", DateTime.Now, AppNumberCurrentAsInt); + await UpdateReaderStatusCommand.ExecuteAsync(false); + CurrentTaskErrorLevel = result; + } + else + { + StatusText += string.Format("{0}: Unable to Authenticate: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + await UpdateReaderStatusCommand.ExecuteAsync(false); + CurrentTaskErrorLevel = result; + } - desfireTask.RunSynchronously(); + } + } } + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } /// /// /// - public ICommand AuthenticateToCardMasterApplicationCommand => new RelayCommand(OnNewAuthenticateToCardMasterApplicationCommand); - private void OnNewAuthenticateToCardMasterApplicationCommand() + public IAsyncRelayCommand ChangeMasterCardKeyCommand => new AsyncRelayCommand(OnNewChangeMasterCardKeyCommand); + private async Task OnNewChangeMasterCardKeyCommand() { CurrentTaskErrorLevel = ERROR.Empty; - - var desfireTask = new Task( - () => + using (var device = ReaderDevice.Instance) + { + if (device != null) { - using (var device = ReaderDevice.Instance) + await UpdateReaderStatusCommand.ExecuteAsync(true); + + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireMasterKeyCurrent) == KEY_ERROR.NO_ERROR) { - if (device != null) + DESFireKeySettings keySettings; + keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; + + keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; + keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; + keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; + keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; + + var result = await device.AuthToMifareDesfireApplication( + CustomConverter.DesfireKeyToCheck, + SelectedDesfireMasterKeyEncryptionTypeCurrent, + 0); + + if (result == ERROR.NoError) { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + StatusText += string.Format("{0}: Successfully Authenticated to App 0\n", DateTime.Now); - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireMasterKeyCurrent) == KEY_ERROR.NO_ERROR) + if (IsValidDesfireMasterKeyCurrent != false && + IsValidDesfireMasterKeyTarget != false) { - var result = device.AuthToMifareDesfireApplication( + result = await device.ChangeMifareDesfireApplicationKey( DesfireMasterKeyCurrent, + 0, SelectedDesfireMasterKeyEncryptionTypeCurrent, - 0); + DesfireMasterKeyTarget, + 0, + 0, + SelectedDesfireMasterKeyEncryptionTypeTarget, 0, 0, keySettings, keyVersionCurrentAsInt); if (result == ERROR.NoError) { - StatusText += string.Format("{0}: Successfully Authenticated to App 0\n", DateTime.Now); + StatusText += string.Format("{0}: Keychange Successfull\n", DateTime.Now); CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } else { - StatusText += string.Format("{0}: {1}: {2}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxUnableToAuthenticate"), result.ToString(CultureInfo.CurrentCulture)); + StatusText += string.Format("{0}: Unable to Change Key: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } - } + else + { + StatusText += string.Format("{0}: Key Error: Wrong Format\n", DateTime.Now); + CurrentTaskErrorLevel = ERROR.AuthenticationError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } + else + { + StatusText += string.Format("{0}: {1}: {2}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxUnableToAuthenticate"), result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; } } - }); + } + else + { + CurrentTaskErrorLevel = ERROR.NotReadyError; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + } - if (CurrentTaskErrorLevel == ERROR.Empty) + if (CurrentTaskErrorLevel == ERROR.NoError) { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + + /// + /// + /// + public IAsyncRelayCommand AuthenticateToCardMasterApplicationCommand => new AsyncRelayCommand(OnNewAuthenticateToCardMasterApplicationCommand); + private async Task OnNewAuthenticateToCardMasterApplicationCommand() + { + CurrentTaskErrorLevel = ERROR.Empty; - desfireTask.ContinueWith((x) => + using (var device = ReaderDevice.Instance) + { + if (device != null) { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else + await UpdateReaderStatusCommand.ExecuteAsync(true); + + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireMasterKeyCurrent) == KEY_ERROR.NO_ERROR) { - IsTaskCompletedSuccessfully = false; - } - }); + var result = await device.AuthToMifareDesfireApplication( + DesfireMasterKeyCurrent, + SelectedDesfireMasterKeyEncryptionTypeCurrent, + 0); - desfireTask.RunSynchronously(); + if (result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Authenticated to App 0\n", DateTime.Now); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + else + { + StatusText += string.Format("{0}: {1}: {2}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxUnableToAuthenticate"), result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + await UpdateReaderStatusCommand.ExecuteAsync(false); + return; + } + + } + } } + if (CurrentTaskErrorLevel == ERROR.NoError) + { + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; + } + await UpdateReaderStatusCommand.ExecuteAsync(false); return; } @@ -2771,75 +2722,65 @@ private void OnNewAuthenticateToCardMasterApplicationCommand() /// /// /// - public void ReadAppSettingsCommand() + public async Task ReadAppSettingsCommand() { CurrentTaskErrorLevel = ERROR.Empty; - var desfireTask = new Task(() => + using (var device = ReaderDevice.Instance) { - using (var device = ReaderDevice.Instance) + if (device != null) { - if (device != null) + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); + var result = await device.GetMifareDesfireAppSettings( + DesfireMasterKeyTarget, + SelectedDesfireAppKeyEncryptionTypeCurrent, + selectedDesfireAppKeyNumberCurrentAsInt, + AppNumberCurrentAsInt); - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) - { - var result = device.GetMifareDesfireAppSettings( - DesfireMasterKeyTarget, - SelectedDesfireAppKeyEncryptionTypeCurrent, - selectedDesfireAppKeyNumberCurrentAsInt, - AppNumberCurrentAsInt); + DESFireKeySettings keySettings; + keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; - DESFireKeySettings keySettings; - keySettings = (DESFireKeySettings)SelectedDesfireAppKeySettingsCreateNewApp; + keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; + keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; + keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; + keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; - keySettings |= IsAllowChangeMKChecked ? (DESFireKeySettings)1 : (DESFireKeySettings)0; - keySettings |= IsAllowListingWithoutMKChecked ? (DESFireKeySettings)2 : (DESFireKeySettings)0; - keySettings |= IsAllowCreateDelWithoutMKChecked ? (DESFireKeySettings)4 : (DESFireKeySettings)0; - keySettings |= IsAllowConfigChangableChecked ? (DESFireKeySettings)8 : (DESFireKeySettings)0; + //desfireChip.FreeMemory = device.GenericChip.FreeMemory; + //desfireChip.UID = device.GenericChip.UID; - //desfireChip.FreeMemory = device.GenericChip.FreeMemory; - //desfireChip.UID = device.GenericChip.UID; + if (IsValidAppNumberCurrent != false && result == ERROR.NoError) + { + StatusText += string.Format("{0}: Successfully Read App Settings of App {1}\n", DateTime.Now, AppNumberCurrentAsInt); - if (IsValidAppNumberCurrent != false && result == ERROR.NoError) + if (((byte)device.DesfireAppKeySetting & (byte)keySettings) != 0) { - StatusText += string.Format("{0}: Successfully Read App Settings of App {1}\n", DateTime.Now, AppNumberCurrentAsInt); - - if (((byte)device.DesfireAppKeySetting & (byte)keySettings) != 0) - { - CurrentTaskErrorLevel = ERROR.NoError; - return; - } - CurrentTaskErrorLevel = ERROR.IsNotTrue; + CurrentTaskErrorLevel = ERROR.NoError; } else { - StatusText += string.Format("{0}: Unable to Authenticate: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); - CurrentTaskErrorLevel = result; + CurrentTaskErrorLevel = ERROR.IsNotTrue; } - } + else + { + StatusText += string.Format("{0}: Unable to Authenticate: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = result; + } + } } - return; - }); + } - if (CurrentTaskErrorLevel == ERROR.Empty) + if (CurrentTaskErrorLevel == ERROR.NoError) { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; } return; @@ -2848,89 +2789,93 @@ public void ReadAppSettingsCommand() /// /// /// - public void DoesAppExistCommand(MifareDesfireChipModel desfireChip) + public async Task DoesAppExistCommand(MifareDesfireChipModel desfireChip) { CurrentTaskErrorLevel = ERROR.Empty; - var desfireTask = new Task(() => + using (var device = ReaderDevice.Instance) { - using (var device = ReaderDevice.Instance) + if (device != null) { - if (device != null) - { - StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - - if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) - { - var result = device.GetMiFareDESFireChipAppIDs( - DesfireAppKeyCurrent, - SelectedDesfireAppKeyEncryptionTypeCurrent); + StatusText = string.Format("{0}: {1}\n", DateTime.Now, ResourceLoader.GetResource("textBoxStatusTextBoxDllLoaded")); - desfireChip.FreeMemory = device.DesfireChip.FreeMemory; - desfireChip.UID = device.GenericChip.UID; + if (CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(DesfireAppKeyCurrent) == KEY_ERROR.NO_ERROR) + { + var result = await device.GetMiFareDESFireChipAppIDs( + DesfireAppKeyCurrent, + SelectedDesfireAppKeyEncryptionTypeCurrent); - // Check if specified App "AppNumberCurrentAsInt" exist - if (IsValidAppNumberCurrent != false && AppNumberCurrentAsInt > 0 && result == ERROR.NoError && Array.Exists(device.DesfireChip.AppIDs, x => x == (uint)AppNumberNewAsInt)) - { - StatusText += string.Format("{0}: Success. App with ID:{1} exists\n", DateTime.Now, AppNumberNewAsInt); + desfireChip.FreeMemory = device.DesfireChip.FreeMemory; + //desfireChip.UID = device.GenericChip.Select(x => x.UID).UID; - CurrentTaskErrorLevel = ERROR.NoError; - } + // Check if specified App "AppNumberCurrentAsInt" exist + if (IsValidAppNumberCurrent != false && AppNumberCurrentAsInt > 0 && result == ERROR.NoError && Array.Exists(device.DesfireChip.AppIDs, x => x == (uint)AppNumberNewAsInt)) + { + StatusText += string.Format("{0}: Success. App with ID:{1} exists\n", DateTime.Now, AppNumberNewAsInt); - // Check if ANY App exists - else if (IsValidAppNumberCurrent != false && AppNumberCurrentAsInt == 0 && result == ERROR.NoError && Array.Exists(device.DesfireChip.AppIDs, x => x > 0)) - { - StatusText += string.Format("{0}: Success. Existing Apps Detected\n", DateTime.Now); + CurrentTaskErrorLevel = ERROR.NoError; + } - CurrentTaskErrorLevel = ERROR.NoError; - } + // Check if ANY App exists + else if (IsValidAppNumberCurrent != false && AppNumberCurrentAsInt == 0 && result == ERROR.NoError && Array.Exists(device.DesfireChip.AppIDs, x => x > 0)) + { + StatusText += string.Format("{0}: Success. Existing Apps Detected\n", DateTime.Now); - // Ooops: Iam not allowed to get the info or Key "DesfireAppKeyCurrent" with "SelectedDesfireAppKeyEncryptionTypeCurrent" is incorrect - else if (IsValidAppNumberCurrent != false && result == ERROR.AuthenticationError) - { - StatusText += string.Format("{0}: Failed. Directory Listing is not allowed and PICC MK is Incorrect.\n", DateTime.Now); + CurrentTaskErrorLevel = ERROR.NoError; + } - CurrentTaskErrorLevel = ERROR.AuthenticationError; - } + // Ooops: Iam not allowed to get the info or Key "DesfireAppKeyCurrent" with "SelectedDesfireAppKeyEncryptionTypeCurrent" is incorrect + else if (IsValidAppNumberCurrent != false && result == ERROR.AuthenticationError) + { + StatusText += string.Format("{0}: Failed. Directory Listing is not allowed and PICC MK is Incorrect.\n", DateTime.Now); - // There are no Apps - else - { - StatusText += string.Format("{0}: No Apps Found: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = ERROR.AuthenticationError; + } - CurrentTaskErrorLevel = ERROR.IsNotTrue; - } + // There are no Apps + else + { + StatusText += string.Format("{0}: No Apps Found: {1}\n", DateTime.Now, result.ToString(CultureInfo.CurrentCulture)); + CurrentTaskErrorLevel = ERROR.IsNotTrue; } + } } - return; - }); + } - if (CurrentTaskErrorLevel == ERROR.Empty) + if (CurrentTaskErrorLevel == ERROR.NoError) { - desfireTask.ContinueWith((x) => - { - if (CurrentTaskErrorLevel == ERROR.NoError) - { - IsTaskCompletedSuccessfully = true; - } - else - { - IsTaskCompletedSuccessfully = false; - } - }); - - desfireTask.RunSynchronously(); + IsTaskCompletedSuccessfully = true; + } + else + { + IsTaskCompletedSuccessfully = false; } - return; + return CurrentTaskErrorLevel; } #endregion #region IUserDialogViewModel Implementation + /// + /// + /// + public IAsyncRelayCommand UpdateReaderStatusCommand => new AsyncRelayCommand(UpdateStatus); + private async Task UpdateStatus(bool isBusy) + { + if (OnUpdateStatus != null) + { + OnUpdateStatus(isBusy); + } + else + { + return; + } + } + [XmlIgnore] public bool IsModal { get; private set; } @@ -2974,6 +2919,9 @@ private void Cancel() } } + [XmlIgnore] + public Action OnUpdateStatus { get; set; } + [XmlIgnore] public Action OnOk { get; set; } diff --git a/RFiDGear/ViewModel/TaskSetupViewModels/MifareUltralightSetupViewModel.cs b/RFiDGear/ViewModel/TaskSetupViewModels/MifareUltralightSetupViewModel.cs index dabc406..17c5a12 100644 --- a/RFiDGear/ViewModel/TaskSetupViewModels/MifareUltralightSetupViewModel.cs +++ b/RFiDGear/ViewModel/TaskSetupViewModels/MifareUltralightSetupViewModel.cs @@ -6,20 +6,22 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; + using MefMvvm.SharedContracts; using MefMvvm.SharedContracts.ViewModel; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using RFiDGear.DataAccessLayer.Remote.FromIO; using RFiDGear.DataAccessLayer; using RFiDGear.Model; -using Log4CSharp; + using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; +using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; @@ -27,6 +29,7 @@ using System.Windows.Input; using System.Xml.Serialization; + namespace RFiDGear.ViewModel { /// @@ -35,7 +38,7 @@ namespace RFiDGear.ViewModel public class MifareUltralightSetupViewModel : ObservableObject, IUserDialogViewModel { #region Fields - private static readonly string FacilityName = "RFiDGear"; + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private MifareUltralightChipModel chipModel; private MifareUltralightPageModel pageModel; @@ -123,7 +126,7 @@ public MifareUltralightSetupViewModel(object _selectedSetupViewModel, Observable } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } @@ -411,6 +414,13 @@ public string SelectedTaskDescription #region Commands + public IAsyncRelayCommand SaveSettings => new AsyncRelayCommand(OnNewSaveSettingsCommand); + private async Task OnNewSaveSettingsCommand() + { + SettingsReaderWriter settings = new SettingsReaderWriter(); + await settings.SaveSettings(); + } + /// /// /// diff --git a/RFiDGear/ViewModel/UpdateNotifierViewModel.cs b/RFiDGear/ViewModel/UpdateNotifierViewModel.cs index be2504f..01aefea 100644 --- a/RFiDGear/ViewModel/UpdateNotifierViewModel.cs +++ b/RFiDGear/ViewModel/UpdateNotifierViewModel.cs @@ -7,7 +7,7 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using MvvmDialogs.ViewModels; +using MVVMDialogs.ViewModels; using System; using System.Collections.Generic; using System.Windows.Input; diff --git a/RFiDGear/app.config b/RFiDGear/app.config index e7a246d..3f21170 100644 --- a/RFiDGear/app.config +++ b/RFiDGear/app.config @@ -1,65 +1,65 @@ - + - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + diff --git a/Setup/Product.wxs b/Setup/Product.wxs index 8110c18..c2cc1ec 100644 --- a/Setup/Product.wxs +++ b/Setup/Product.wxs @@ -1,5 +1,6 @@ - + - + + + + - - - - - - + + + @@ -242,6 +245,7 @@ + @@ -333,6 +337,7 @@ + @@ -357,7 +362,7 @@ - + diff --git a/debugParam.txt b/debugParam.txt new file mode 100644 index 0000000..d98b10a --- /dev/null +++ b/debugParam.txt @@ -0,0 +1 @@ +#REPORTTARGETPATH="D:\CardCheck_data\KP-000005-5_final.pdf" REPORTTEMPLATEFILE="D:\CardCheck_data\KP-000005-5_.pdf" CUSTOMPROJECTFILE="D:\CardCheck_data\KPruefung_Vorlagen\00_RFID_Gear_Vorlage\CardCheckAssistant_FreeMem.rfPrj" $JOBNUMBER="KP-000005" $CHIPNUMBER="5" AUTORUN=1 \ No newline at end of file