From 6c78f0c769fe70353e42a7389e0583a5c65cea8a Mon Sep 17 00:00:00 2001 From: Natalia Portillo Date: Sat, 22 Aug 2020 21:37:02 +0100 Subject: [PATCH] Code refactor. --- apprepodbmgr.Core/AlgoEnum.cs | 4 +- apprepodbmgr.Core/Checksum.cs | 410 ++++--- apprepodbmgr.Core/Context.cs | 2 +- apprepodbmgr.Core/DBOps.cs | 166 +-- apprepodbmgr.Core/DetectImageFormat.cs | 22 +- apprepodbmgr.Core/DetectOS.cs | 95 +- apprepodbmgr.Core/IO.cs | 53 +- apprepodbmgr.Core/PlatformID.cs | 147 +-- apprepodbmgr.Core/PluginBase.cs | 104 +- apprepodbmgr.Core/SQLite.cs | 46 +- apprepodbmgr.Core/Schema.cs | 83 +- apprepodbmgr.Core/Settings.cs | 207 ++-- apprepodbmgr.Core/Symlinks.cs | 8 +- apprepodbmgr.Core/Workers/Clamd.cs | 126 ++- apprepodbmgr.Core/Workers/Compression.cs | 352 ++++-- apprepodbmgr.Core/Workers/Database.cs | 183 +-- apprepodbmgr.Core/Workers/DiscImageChef.cs | 561 ++++++---- apprepodbmgr.Core/Workers/Files.cs | 603 ++++++---- apprepodbmgr.Core/Workers/Miscellaneous.cs | 27 +- apprepodbmgr.Core/Workers/VirusTotal.cs | 118 +- apprepodbmgr.Eto.Desktop/Program.cs | 7 +- apprepodbmgr.Eto/WrappersForEto.cs | 114 +- apprepodbmgr.Eto/dlgAdd.xeto.cs | 1112 ++++++++++-------- apprepodbmgr.Eto/dlgBlockMedia.xeto.cs | 632 ++++++++--- apprepodbmgr.Eto/dlgFilesystem.xeto.cs | 129 ++- apprepodbmgr.Eto/dlgImportMetadata.xeto.cs | 171 ++- apprepodbmgr.Eto/dlgMetadata.xeto.cs | 1183 +++++++++++++------- apprepodbmgr.Eto/dlgOpticalDisc.xeto.cs | 1177 ++++++++++++------- apprepodbmgr.Eto/dlgSettings.xeto.cs | 173 +-- apprepodbmgr.Eto/frmMain.xeto.cs | 1001 +++++++++-------- apprepodbmgr.Eto/pnlDescription.xeto.cs | 43 +- apprepodbmgr.Eto/pnlStrings.xeto.cs | 22 +- apprepodbmgr.Eto/pnlVersions.xeto.cs | 23 +- 33 files changed, 5624 insertions(+), 3480 deletions(-) diff --git a/apprepodbmgr.Core/AlgoEnum.cs b/apprepodbmgr.Core/AlgoEnum.cs index 6faa651..adca4a5 100644 --- a/apprepodbmgr.Core/AlgoEnum.cs +++ b/apprepodbmgr.Core/AlgoEnum.cs @@ -30,9 +30,7 @@ namespace apprepodbmgr.Core { public enum AlgoEnum { - GZip, - BZip2, - LZMA, + GZip, BZip2, LZMA, LZip } } \ No newline at end of file diff --git a/apprepodbmgr.Core/Checksum.cs b/apprepodbmgr.Core/Checksum.cs index c7656e4..61457c2 100644 --- a/apprepodbmgr.Core/Checksum.cs +++ b/apprepodbmgr.Core/Checksum.cs @@ -37,41 +37,41 @@ using Schemas; namespace apprepodbmgr.Core { - class Checksum + internal class Checksum { - Adler32Context adler32ctx; - adlerPacket adlerPkt; - Thread adlerThread; - Crc16Context crc16ctx; - crc16Packet crc16Pkt; - Thread crc16Thread; - Crc32Context crc32ctx; - crc32Packet crc32Pkt; - Thread crc32Thread; - Crc64Context crc64ctx; - crc64Packet crc64Pkt; - Thread crc64Thread; - Md5Context md5ctx; - md5Packet md5Pkt; - Thread md5Thread; - Ripemd160Context ripemd160ctx; - ripemd160Packet ripemd160Pkt; - Thread ripemd160Thread; - Sha1Context sha1ctx; - sha1Packet sha1Pkt; - Thread sha1Thread; - Sha256Context sha256ctx; - sha256Packet sha256Pkt; - Thread sha256Thread; - Sha384Context sha384ctx; - sha384Packet sha384Pkt; - Thread sha384Thread; - Sha512Context sha512ctx; - sha512Packet sha512Pkt; - Thread sha512Thread; - spamsumPacket spamsumPkt; - Thread spamsumThread; - SpamSumContext ssctx; + readonly Adler32Context adler32ctx; + adlerPacket adlerPkt; + Thread adlerThread; + readonly Crc16Context crc16ctx; + crc16Packet crc16Pkt; + Thread crc16Thread; + readonly Crc32Context crc32ctx; + crc32Packet crc32Pkt; + Thread crc32Thread; + readonly Crc64Context crc64ctx; + crc64Packet crc64Pkt; + Thread crc64Thread; + readonly Md5Context md5ctx; + md5Packet md5Pkt; + Thread md5Thread; + readonly Ripemd160Context ripemd160ctx; + ripemd160Packet ripemd160Pkt; + Thread ripemd160Thread; + readonly Sha1Context sha1ctx; + sha1Packet sha1Pkt; + Thread sha1Thread; + readonly Sha256Context sha256ctx; + sha256Packet sha256Pkt; + Thread sha256Thread; + readonly Sha384Context sha384ctx; + sha384Packet sha384Pkt; + Thread sha384Thread; + readonly Sha512Context sha512ctx; + sha512Packet sha512Pkt; + Thread sha512Thread; + spamsumPacket spamsumPkt; + Thread spamsumThread; + readonly SpamSumContext ssctx; internal Checksum() { @@ -111,17 +111,17 @@ namespace apprepodbmgr.Core sha512Pkt = new sha512Packet(); spamsumPkt = new spamsumPacket(); - adlerPkt.context = adler32ctx; - crc16Pkt.context = crc16ctx; - crc32Pkt.context = crc32ctx; - crc64Pkt.context = crc64ctx; - md5Pkt.context = md5ctx; + adlerPkt.context = adler32ctx; + crc16Pkt.context = crc16ctx; + crc32Pkt.context = crc32ctx; + crc64Pkt.context = crc64ctx; + md5Pkt.context = md5ctx; ripemd160Pkt.context = ripemd160ctx; - sha1Pkt.context = sha1ctx; - sha256Pkt.context = sha256ctx; - sha384Pkt.context = sha384ctx; - sha512Pkt.context = sha512ctx; - spamsumPkt.context = ssctx; + sha1Pkt.context = sha1ctx; + sha256Pkt.context = sha256ctx; + sha384Pkt.context = sha384ctx; + sha512Pkt.context = sha512ctx; + spamsumPkt.context = ssctx; } internal void Update(byte[] data) @@ -149,9 +149,17 @@ namespace apprepodbmgr.Core spamsumPkt.data = data; spamsumThread.Start(spamsumPkt); - while(adlerThread.IsAlive || crc16Thread.IsAlive || crc32Thread.IsAlive || crc64Thread.IsAlive || - md5Thread.IsAlive || ripemd160Thread.IsAlive || sha1Thread.IsAlive || sha256Thread.IsAlive || - sha384Thread.IsAlive || sha512Thread.IsAlive || spamsumThread.IsAlive) { } + while(adlerThread.IsAlive || + crc16Thread.IsAlive || + crc32Thread.IsAlive || + crc64Thread.IsAlive || + md5Thread.IsAlive || + ripemd160Thread.IsAlive || + sha1Thread.IsAlive || + sha256Thread.IsAlive || + sha384Thread.IsAlive || + sha512Thread.IsAlive || + spamsumThread.IsAlive) {} adlerThread = new Thread(updateAdler); crc16Thread = new Thread(updateCRC16); @@ -170,37 +178,92 @@ namespace apprepodbmgr.Core { List chks = new List(); - ChecksumType chk = new ChecksumType {type = ChecksumTypeType.adler32, Value = adler32ctx.End()}; + var chk = new ChecksumType + { + type = ChecksumTypeType.adler32, + Value = adler32ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.crc16, Value = crc16ctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.crc16, + Value = crc16ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.crc32, Value = crc32ctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.crc32, + Value = crc32ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.crc64, Value = crc64ctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.crc64, + Value = crc64ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.md5, Value = md5ctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.md5, + Value = md5ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.ripemd160, Value = ripemd160ctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.ripemd160, + Value = ripemd160ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.sha1, Value = sha1ctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.sha1, + Value = sha1ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.sha256, Value = sha256ctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.sha256, + Value = sha256ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.sha384, Value = sha384ctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.sha384, + Value = sha384ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.sha512, Value = sha512ctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.sha512, + Value = sha512ctx.End() + }; + chks.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.spamsum, Value = ssctx.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.spamsum, + Value = ssctx.End() + }; + chks.Add(chk); return chks; @@ -208,53 +271,53 @@ namespace apprepodbmgr.Core internal static List GetChecksums(byte[] data) { - Adler32Context adler32ctxData = new Adler32Context(); - Crc16Context crc16ctxData = new Crc16Context(); - Crc32Context crc32ctxData = new Crc32Context(); - Crc64Context crc64ctxData = new Crc64Context(); - Md5Context md5ctxData = new Md5Context(); - Ripemd160Context ripemd160ctxData = new Ripemd160Context(); - Sha1Context sha1ctxData = new Sha1Context(); - Sha256Context sha256ctxData = new Sha256Context(); - Sha384Context sha384ctxData = new Sha384Context(); - Sha512Context sha512ctxData = new Sha512Context(); - SpamSumContext ssctxData = new SpamSumContext(); + var adler32ctxData = new Adler32Context(); + var crc16ctxData = new Crc16Context(); + var crc32ctxData = new Crc32Context(); + var crc64ctxData = new Crc64Context(); + var md5ctxData = new Md5Context(); + var ripemd160ctxData = new Ripemd160Context(); + var sha1ctxData = new Sha1Context(); + var sha256ctxData = new Sha256Context(); + var sha384ctxData = new Sha384Context(); + var sha512ctxData = new Sha512Context(); + var ssctxData = new SpamSumContext(); - Thread adlerThreadData = new Thread(updateAdler); - Thread crc16ThreadData = new Thread(updateCRC16); - Thread crc32ThreadData = new Thread(updateCRC32); - Thread crc64ThreadData = new Thread(updateCRC64); - Thread md5ThreadData = new Thread(updateMD5); - Thread ripemd160ThreadData = new Thread(updateRIPEMD160); - Thread sha1ThreadData = new Thread(updateSHA1); - Thread sha256ThreadData = new Thread(updateSHA256); - Thread sha384ThreadData = new Thread(updateSHA384); - Thread sha512ThreadData = new Thread(updateSHA512); - Thread spamsumThreadData = new Thread(updateSpamSum); + var adlerThreadData = new Thread(updateAdler); + var crc16ThreadData = new Thread(updateCRC16); + var crc32ThreadData = new Thread(updateCRC32); + var crc64ThreadData = new Thread(updateCRC64); + var md5ThreadData = new Thread(updateMD5); + var ripemd160ThreadData = new Thread(updateRIPEMD160); + var sha1ThreadData = new Thread(updateSHA1); + var sha256ThreadData = new Thread(updateSHA256); + var sha384ThreadData = new Thread(updateSHA384); + var sha512ThreadData = new Thread(updateSHA512); + var spamsumThreadData = new Thread(updateSpamSum); - adlerPacket adlerPktData = new adlerPacket(); - crc16Packet crc16PktData = new crc16Packet(); - crc32Packet crc32PktData = new crc32Packet(); - crc64Packet crc64PktData = new crc64Packet(); - md5Packet md5PktData = new md5Packet(); - ripemd160Packet ripemd160PktData = new ripemd160Packet(); - sha1Packet sha1PktData = new sha1Packet(); - sha256Packet sha256PktData = new sha256Packet(); - sha384Packet sha384PktData = new sha384Packet(); - sha512Packet sha512PktData = new sha512Packet(); - spamsumPacket spamsumPktData = new spamsumPacket(); + var adlerPktData = new adlerPacket(); + var crc16PktData = new crc16Packet(); + var crc32PktData = new crc32Packet(); + var crc64PktData = new crc64Packet(); + var md5PktData = new md5Packet(); + var ripemd160PktData = new ripemd160Packet(); + var sha1PktData = new sha1Packet(); + var sha256PktData = new sha256Packet(); + var sha384PktData = new sha384Packet(); + var sha512PktData = new sha512Packet(); + var spamsumPktData = new spamsumPacket(); - adlerPktData.context = adler32ctxData; - crc16PktData.context = crc16ctxData; - crc32PktData.context = crc32ctxData; - crc64PktData.context = crc64ctxData; - md5PktData.context = md5ctxData; + adlerPktData.context = adler32ctxData; + crc16PktData.context = crc16ctxData; + crc32PktData.context = crc32ctxData; + crc64PktData.context = crc64ctxData; + md5PktData.context = md5ctxData; ripemd160PktData.context = ripemd160ctxData; - sha1PktData.context = sha1ctxData; - sha256PktData.context = sha256ctxData; - sha384PktData.context = sha384ctxData; - sha512PktData.context = sha512ctxData; - spamsumPktData.context = ssctxData; + sha1PktData.context = sha1ctxData; + sha256PktData.context = sha256ctxData; + sha384PktData.context = sha384ctxData; + sha512PktData.context = sha512ctxData; + spamsumPktData.context = ssctxData; adlerPktData.data = data; adlerThreadData.Start(adlerPktData); @@ -279,44 +342,106 @@ namespace apprepodbmgr.Core spamsumPktData.data = data; spamsumThreadData.Start(spamsumPktData); - while(adlerThreadData.IsAlive || crc16ThreadData.IsAlive || crc32ThreadData.IsAlive || - crc64ThreadData.IsAlive || md5ThreadData.IsAlive || ripemd160ThreadData.IsAlive || - sha1ThreadData.IsAlive || sha256ThreadData.IsAlive || sha384ThreadData.IsAlive || - sha512ThreadData.IsAlive || spamsumThreadData.IsAlive) { } + while(adlerThreadData.IsAlive || + crc16ThreadData.IsAlive || + crc32ThreadData.IsAlive || + crc64ThreadData.IsAlive || + md5ThreadData.IsAlive || + ripemd160ThreadData.IsAlive || + sha1ThreadData.IsAlive || + sha256ThreadData.IsAlive || + sha384ThreadData.IsAlive || + sha512ThreadData.IsAlive || + spamsumThreadData.IsAlive) {} List dataChecksums = new List(); - ChecksumType chk = new ChecksumType {type = ChecksumTypeType.adler32, Value = adler32ctxData.End()}; + var chk = new ChecksumType + { + type = ChecksumTypeType.adler32, + Value = adler32ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.crc16, Value = crc16ctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.crc16, + Value = crc16ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.crc32, Value = crc32ctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.crc32, + Value = crc32ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.crc64, Value = crc64ctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.crc64, + Value = crc64ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.md5, Value = md5ctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.md5, + Value = md5ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.ripemd160, Value = ripemd160ctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.ripemd160, + Value = ripemd160ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.sha1, Value = sha1ctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.sha1, + Value = sha1ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.sha256, Value = sha256ctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.sha256, + Value = sha256ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.sha384, Value = sha384ctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.sha384, + Value = sha384ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.sha512, Value = sha512ctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.sha512, + Value = sha512ctxData.End() + }; + dataChecksums.Add(chk); - chk = new ChecksumType {type = ChecksumTypeType.spamsum, Value = ssctxData.End()}; + chk = new ChecksumType + { + type = ChecksumTypeType.spamsum, + Value = ssctxData.End() + }; + dataChecksums.Add(chk); return dataChecksums; @@ -389,60 +514,29 @@ namespace apprepodbmgr.Core public byte[] data; } - static void updateAdler(object packet) - { - ((adlerPacket)packet).context.Update(((adlerPacket)packet).data); - } + static void updateAdler(object packet) => ((adlerPacket)packet).context.Update(((adlerPacket)packet).data); - static void updateCRC16(object packet) - { - ((crc16Packet)packet).context.Update(((crc16Packet)packet).data); - } + static void updateCRC16(object packet) => ((crc16Packet)packet).context.Update(((crc16Packet)packet).data); - static void updateCRC32(object packet) - { - ((crc32Packet)packet).context.Update(((crc32Packet)packet).data); - } + static void updateCRC32(object packet) => ((crc32Packet)packet).context.Update(((crc32Packet)packet).data); - static void updateCRC64(object packet) - { - ((crc64Packet)packet).context.Update(((crc64Packet)packet).data); - } + static void updateCRC64(object packet) => ((crc64Packet)packet).context.Update(((crc64Packet)packet).data); - static void updateMD5(object packet) - { - ((md5Packet)packet).context.Update(((md5Packet)packet).data); - } + static void updateMD5(object packet) => ((md5Packet)packet).context.Update(((md5Packet)packet).data); - static void updateRIPEMD160(object packet) - { + static void updateRIPEMD160(object packet) => ((ripemd160Packet)packet).context.Update(((ripemd160Packet)packet).data); - } - static void updateSHA1(object packet) - { - ((sha1Packet)packet).context.Update(((sha1Packet)packet).data); - } + static void updateSHA1(object packet) => ((sha1Packet)packet).context.Update(((sha1Packet)packet).data); - static void updateSHA256(object packet) - { - ((sha256Packet)packet).context.Update(((sha256Packet)packet).data); - } + static void updateSHA256(object packet) => ((sha256Packet)packet).context.Update(((sha256Packet)packet).data); - static void updateSHA384(object packet) - { - ((sha384Packet)packet).context.Update(((sha384Packet)packet).data); - } + static void updateSHA384(object packet) => ((sha384Packet)packet).context.Update(((sha384Packet)packet).data); - static void updateSHA512(object packet) - { - ((sha512Packet)packet).context.Update(((sha512Packet)packet).data); - } + static void updateSHA512(object packet) => ((sha512Packet)packet).context.Update(((sha512Packet)packet).data); - static void updateSpamSum(object packet) - { + static void updateSpamSum(object packet) => ((spamsumPacket)packet).context.Update(((spamsumPacket)packet).data); - } #endregion Threading helpers } } \ No newline at end of file diff --git a/apprepodbmgr.Core/Context.cs b/apprepodbmgr.Core/Context.cs index 9700b86..c9625f1 100644 --- a/apprepodbmgr.Core/Context.cs +++ b/apprepodbmgr.Core/Context.cs @@ -68,7 +68,7 @@ namespace apprepodbmgr.Core Workers.FinishedWithText += CheckUnarFinished; Workers.Failed += CheckUnarFailed; - Thread thdCheckUnar = new Thread(Workers.CheckUnar); + var thdCheckUnar = new Thread(Workers.CheckUnar); thdCheckUnar.Start(); } diff --git a/apprepodbmgr.Core/DBOps.cs b/apprepodbmgr.Core/DBOps.cs index 013a0c2..3771c59 100644 --- a/apprepodbmgr.Core/DBOps.cs +++ b/apprepodbmgr.Core/DBOps.cs @@ -111,14 +111,14 @@ namespace apprepodbmgr.Core IDbCommand dbcmd = dbCon.CreateCommand(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dbcmd.CommandText = SQL; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; foreach(DataRow dRow in dataTable.Rows) { - DbEntry fEntry = new DbEntry + var fEntry = new DbEntry { Id = long.Parse(dRow["id"].ToString()), Developer = dRow["developer"].ToString(), @@ -138,9 +138,15 @@ namespace apprepodbmgr.Core Mdid = dRow["mdid"].ToString() }; - if(dRow["xml"] != DBNull.Value) fEntry.Xml = (byte[])dRow["xml"]; - if(dRow["json"] != DBNull.Value) fEntry.Json = (byte[])dRow["json"]; - if(dRow["icon"] != DBNull.Value) fEntry.Icon = (byte[])dRow["icon"]; + if(dRow["xml"] != DBNull.Value) + fEntry.Xml = (byte[])dRow["xml"]; + + if(dRow["json"] != DBNull.Value) + fEntry.Json = (byte[])dRow["json"]; + + if(dRow["icon"] != DBNull.Value) + fEntry.Icon = (byte[])dRow["icon"]; + entries.Add(fEntry); } @@ -363,13 +369,14 @@ namespace apprepodbmgr.Core param1.Value = hash; dbcmd.Parameters.Add(param1); dbcmd.CommandText = "SELECT * FROM files WHERE sha256 = @hash"; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; - foreach(DataRow dRow in dataTable.Rows) return true; + foreach(DataRow dRow in dataTable.Rows) + return true; return false; } @@ -380,8 +387,15 @@ namespace apprepodbmgr.Core dbcmd.CommandText = "SELECT COUNT(*) FROM files"; object count = dbcmd.ExecuteScalar(); dbcmd.Dispose(); - try { return Convert.ToUInt64(count); } - catch { return 0; } + + try + { + return Convert.ToUInt64(count); + } + catch + { + return 0; + } } public DbFile GetFile(string hash) @@ -391,14 +405,14 @@ namespace apprepodbmgr.Core IDbCommand dbcmd = dbCon.CreateCommand(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dbcmd.CommandText = sql; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; foreach(DataRow dRow in dataTable.Rows) { - DbFile fEntry = new DbFile + var fEntry = new DbFile { Id = ulong.Parse(dRow["id"].ToString()), Sha256 = dRow["sha256"].ToString(), @@ -407,14 +421,20 @@ namespace apprepodbmgr.Core Length = long.Parse(dRow["length"].ToString()) }; - if(dRow["hasvirus"] == DBNull.Value) fEntry.HasVirus = null; - else fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString()); - if(dRow["clamtime"] == DBNull.Value) fEntry.ClamTime = null; - else fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString()); - if(dRow["vtotaltime"] == DBNull.Value) fEntry.VirusTotalTime = null; + if(dRow["hasvirus"] == DBNull.Value) + fEntry.HasVirus = null; else - fEntry.VirusTotalTime = - DateTime.Parse(dRow["vtotaltime"].ToString()); + fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString()); + + if(dRow["clamtime"] == DBNull.Value) + fEntry.ClamTime = null; + else + fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString()); + + if(dRow["vtotaltime"] == DBNull.Value) + fEntry.VirusTotalTime = null; + else + fEntry.VirusTotalTime = DateTime.Parse(dRow["vtotaltime"].ToString()); return fEntry; } @@ -431,14 +451,14 @@ namespace apprepodbmgr.Core IDbCommand dbcmd = dbCon.CreateCommand(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dbcmd.CommandText = sql; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; foreach(DataRow dRow in dataTable.Rows) { - DbFile fEntry = new DbFile + var fEntry = new DbFile { Id = ulong.Parse(dRow["id"].ToString()), Sha256 = dRow["sha256"].ToString(), @@ -447,14 +467,20 @@ namespace apprepodbmgr.Core Length = long.Parse(dRow["length"].ToString()) }; - if(dRow["hasvirus"] == DBNull.Value) fEntry.HasVirus = null; - else fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString()); - if(dRow["clamtime"] == DBNull.Value) fEntry.ClamTime = null; - else fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString()); - if(dRow["vtotaltime"] == DBNull.Value) fEntry.VirusTotalTime = null; + if(dRow["hasvirus"] == DBNull.Value) + fEntry.HasVirus = null; else - fEntry.VirusTotalTime = - DateTime.Parse(dRow["vtotaltime"].ToString()); + fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString()); + + if(dRow["clamtime"] == DBNull.Value) + fEntry.ClamTime = null; + else + fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString()); + + if(dRow["vtotaltime"] == DBNull.Value) + fEntry.VirusTotalTime = null; + else + fEntry.VirusTotalTime = DateTime.Parse(dRow["vtotaltime"].ToString()); entries.Add(fEntry); } @@ -471,14 +497,14 @@ namespace apprepodbmgr.Core IDbCommand dbcmd = dbCon.CreateCommand(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dbcmd.CommandText = SQL; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; foreach(DataRow dRow in dataTable.Rows) { - DbFile fEntry = new DbFile + var fEntry = new DbFile { Id = ulong.Parse(dRow["id"].ToString()), Sha256 = dRow["sha256"].ToString(), @@ -487,14 +513,20 @@ namespace apprepodbmgr.Core Length = long.Parse(dRow["length"].ToString()) }; - if(dRow["hasvirus"] == DBNull.Value) fEntry.HasVirus = null; - else fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString()); - if(dRow["clamtime"] == DBNull.Value) fEntry.ClamTime = null; - else fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString()); - if(dRow["vtotaltime"] == DBNull.Value) fEntry.VirusTotalTime = null; + if(dRow["hasvirus"] == DBNull.Value) + fEntry.HasVirus = null; else - fEntry.VirusTotalTime = - DateTime.Parse(dRow["vtotaltime"].ToString()); + fEntry.HasVirus = bool.Parse(dRow["hasvirus"].ToString()); + + if(dRow["clamtime"] == DBNull.Value) + fEntry.ClamTime = null; + else + fEntry.ClamTime = DateTime.Parse(dRow["clamtime"].ToString()); + + if(dRow["vtotaltime"] == DBNull.Value) + fEntry.VirusTotalTime = null; + else + fEntry.VirusTotalTime = DateTime.Parse(dRow["vtotaltime"].ToString()); entries.Add(fEntry); } @@ -683,16 +715,11 @@ namespace apprepodbmgr.Core IDbTransaction trans = dbCon.BeginTransaction(); dbcmd.Transaction = trans; - string sql = $"DROP TABLE IF EXISTS `app_{id}`;\n\n" + - $"CREATE TABLE IF NOT EXISTS `app_{id}` (\n" + - " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + - " `path` VARCHAR(8192) NOT NULL,\n" + - " `sha256` VARCHAR(64) NOT NULL,\n\n" + - " `length` BIGINT NOT NULL,\n" + - " `creation` DATETIME NULL,\n" + - " `access` DATETIME NULL,\n" + - " `modification` DATETIME NULL,\n" + - " `attributes` INTEGER NULL);\n\n" + + string sql = $"DROP TABLE IF EXISTS `app_{id}`;\n\n" + $"CREATE TABLE IF NOT EXISTS `app_{id}` (\n" + + " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + " `path` VARCHAR(8192) NOT NULL,\n" + + " `sha256` VARCHAR(64) NOT NULL,\n\n" + " `length` BIGINT NOT NULL,\n" + + " `creation` DATETIME NULL,\n" + " `access` DATETIME NULL,\n" + + " `modification` DATETIME NULL,\n" + " `attributes` INTEGER NULL);\n\n" + $"CREATE UNIQUE INDEX `app_{id}_id_UNIQUE` ON `app_{id}` (`id` ASC);\n\n" + $"CREATE INDEX `app_{id}_path_idx` ON `app_{id}` (`path` ASC);"; @@ -706,14 +733,11 @@ namespace apprepodbmgr.Core trans = dbCon.BeginTransaction(); dbcmd.Transaction = trans; - sql = $"DROP TABLE IF EXISTS `app_{id}_folders`;\n\n" + - $"CREATE TABLE IF NOT EXISTS `app_{id}_folders` (\n" + - " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + - " `path` VARCHAR(8192) NOT NULL,\n" + - " `creation` DATETIME NULL,\n" + - " `access` DATETIME NULL,\n" + - " `modification` DATETIME NULL,\n" + - " `attributes` INTEGER NULL);\n\n" + + sql = $"DROP TABLE IF EXISTS `app_{id}_folders`;\n\n" + + $"CREATE TABLE IF NOT EXISTS `app_{id}_folders` (\n" + " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + + " `path` VARCHAR(8192) NOT NULL,\n" + " `creation` DATETIME NULL,\n" + + " `access` DATETIME NULL,\n" + " `modification` DATETIME NULL,\n" + + " `attributes` INTEGER NULL);\n\n" + $"CREATE UNIQUE INDEX `app_{id}_folders_id_UNIQUE` ON `app_{id}_folders` (`id` ASC);\n\n" + $"CREATE INDEX `app_{id}_folders_path_idx` ON `app_{id}_folders` (`path` ASC);"; @@ -736,13 +760,14 @@ namespace apprepodbmgr.Core param1.Value = hash; dbcmd.Parameters.Add(param1); dbcmd.CommandText = $"SELECT * FROM `app_{appId}` WHERE sha256 = @hash"; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; - foreach(DataRow dRow in dataTable.Rows) return true; + foreach(DataRow dRow in dataTable.Rows) + return true; return false; } @@ -757,13 +782,14 @@ namespace apprepodbmgr.Core param1.Value = mdid; dbcmd.Parameters.Add(param1); dbcmd.CommandText = "SELECT * FROM `apps` WHERE mdid = @mdid"; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; - foreach(DataRow dRow in dataTable.Rows) return true; + foreach(DataRow dRow in dataTable.Rows) + return true; return false; } @@ -777,14 +803,14 @@ namespace apprepodbmgr.Core IDbCommand dbcmd = dbCon.CreateCommand(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dbcmd.CommandText = sql; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; foreach(DataRow dRow in dataTable.Rows) { - DbAppFile fEntry = new DbAppFile + var fEntry = new DbAppFile { Id = ulong.Parse(dRow["id"].ToString()), Path = dRow["path"].ToString(), @@ -811,14 +837,14 @@ namespace apprepodbmgr.Core IDbCommand dbcmd = dbCon.CreateCommand(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dbcmd.CommandText = sql; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; foreach(DataRow dRow in dataTable.Rows) { - DbFolder fEntry = new DbFolder + var fEntry = new DbFolder { Id = ulong.Parse(dRow["id"].ToString()), Path = dRow["path"].ToString(), @@ -875,8 +901,10 @@ namespace apprepodbmgr.Core public bool HasSymlinks(long appId) { IDbCommand dbcmd = dbCon.CreateCommand(); + dbcmd.CommandText = $"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'app_{appId}_symlinks'"; + object count = dbcmd.ExecuteScalar(); dbcmd.Dispose(); @@ -889,13 +917,11 @@ namespace apprepodbmgr.Core IDbTransaction trans = dbCon.BeginTransaction(); dbcmd.Transaction = trans; - dbcmd.CommandText = - $"DROP TABLE IF EXISTS `app_{id}_symlinks`;\n\n" + - $"CREATE TABLE IF NOT EXISTS `app_{id}_symlinks` (\n" + - " `path` VARCHAR(8192) PRIMARY KEY,\n" + - " `target` VARCHAR(8192) NOT NULL);\n\n" + - $"CREATE UNIQUE INDEX `app_{id}_symlinks_path_UNIQUE` ON `app_{id}_symlinks` (`path` ASC);\n\n" + - $"CREATE INDEX `app_{id}_symlinks_target_idx` ON `app_{id}_symlinks` (`target` ASC);"; + dbcmd.CommandText = $"DROP TABLE IF EXISTS `app_{id}_symlinks`;\n\n" + + $"CREATE TABLE IF NOT EXISTS `app_{id}_symlinks` (\n" + + " `path` VARCHAR(8192) PRIMARY KEY,\n" + " `target` VARCHAR(8192) NOT NULL);\n\n" + + $"CREATE UNIQUE INDEX `app_{id}_symlinks_path_UNIQUE` ON `app_{id}_symlinks` (`path` ASC);\n\n" + + $"CREATE INDEX `app_{id}_symlinks_target_idx` ON `app_{id}_symlinks` (`target` ASC);"; dbcmd.ExecuteNonQuery(); trans.Commit(); @@ -946,7 +972,7 @@ namespace apprepodbmgr.Core IDbCommand dbcmd = dbCon.CreateCommand(); IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter(); dbcmd.CommandText = sql; - DataSet dataSet = new DataSet(); + var dataSet = new DataSet(); dataAdapter.SelectCommand = dbcmd; dataAdapter.Fill(dataSet); DataTable dataTable = dataSet.Tables[0]; diff --git a/apprepodbmgr.Core/DetectImageFormat.cs b/apprepodbmgr.Core/DetectImageFormat.cs index c6dff5e..2c0ebb4 100644 --- a/apprepodbmgr.Core/DetectImageFormat.cs +++ b/apprepodbmgr.Core/DetectImageFormat.cs @@ -43,7 +43,7 @@ namespace apprepodbmgr.Core { try { - PluginBase plugins = new PluginBase(); + var plugins = new PluginBase(); IMediaImage imageFormat = null; @@ -53,37 +53,45 @@ namespace apprepodbmgr.Core ) try { - if(!imageplugin.Identify(imageFilter)) continue; + if(!imageplugin.Identify(imageFilter)) + continue; imageFormat = imageplugin; + break; } #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body - catch { } + catch {} #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body // Check only RAW plugin - if(imageFormat != null) return imageFormat; + if(imageFormat != null) + return imageFormat; foreach(IMediaImage imageplugin in plugins.ImagePluginsList.Values.Where(p => p.Id == new Guid("12345678-AAAA-BBBB-CCCC-123456789000")) ) try { - if(!imageplugin.Identify(imageFilter)) continue; + if(!imageplugin.Identify(imageFilter)) + continue; imageFormat = imageplugin; + break; } #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body - catch { } + catch {} #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body // Still not recognized return imageFormat; } - catch { return null; } + catch + { + return null; + } } } } \ No newline at end of file diff --git a/apprepodbmgr.Core/DetectOS.cs b/apprepodbmgr.Core/DetectOS.cs index f21157c..2f2d2dd 100644 --- a/apprepodbmgr.Core/DetectOS.cs +++ b/apprepodbmgr.Core/DetectOS.cs @@ -51,27 +51,31 @@ namespace DiscImageChef.Interop public static PlatformID GetRealPlatformID() { - if((int)Environment.OSVersion.Platform < 4 || (int)Environment.OSVersion.Platform == 5) + if((int)Environment.OSVersion.Platform < 4 || + (int)Environment.OSVersion.Platform == 5) return (PlatformID)(int)Environment.OSVersion.Platform; int error = uname(out utsname unixname); - if(error != 0) throw new Exception($"Unhandled exception calling uname: {Marshal.GetLastWin32Error()}"); + + if(error != 0) + throw new Exception($"Unhandled exception calling uname: {Marshal.GetLastWin32Error()}"); switch(unixname.sysname) { // TODO: Differentiate Linux, Android, Tizen case "Linux": { - #if __ANDROID__ + #if __ANDROID__ return PlatformID.Android; - #else + #else return PlatformID.Linux; - #endif + #endif } case "Darwin": { IntPtr pLen = Marshal.AllocHGlobal(sizeof(int)); int osx_error = OSX_sysctlbyname("hw.machine", IntPtr.Zero, pLen, IntPtr.Zero, 0); + if(osx_error != 0) { Marshal.FreeHGlobal(pLen); @@ -81,7 +85,8 @@ namespace DiscImageChef.Interop int length = Marshal.ReadInt32(pLen); IntPtr pStr = Marshal.AllocHGlobal(length); - osx_error = OSX_sysctlbyname("hw.machine", pStr, pLen, IntPtr.Zero, 0); + osx_error = OSX_sysctlbyname("hw.machine", pStr, pLen, IntPtr.Zero, 0); + if(osx_error != 0) { Marshal.FreeHGlobal(pStr); @@ -95,22 +100,23 @@ namespace DiscImageChef.Interop Marshal.FreeHGlobal(pStr); Marshal.FreeHGlobal(pLen); - if(machine.StartsWith("iPad", StringComparison.Ordinal) || - machine.StartsWith("iPod", StringComparison.Ordinal) || - machine.StartsWith("iPhone", StringComparison.Ordinal)) return PlatformID.iOS; + if(machine.StartsWith("iPad", StringComparison.Ordinal) || + machine.StartsWith("iPod", StringComparison.Ordinal) || + machine.StartsWith("iPhone", StringComparison.Ordinal)) + return PlatformID.iOS; return PlatformID.MacOSX; } case "GNU": return PlatformID.Hurd; case "FreeBSD": case "GNU/kFreeBSD": return PlatformID.FreeBSD; - case "DragonFly": return PlatformID.DragonFly; - case "Haiku": return PlatformID.Haiku; - case "HP-UX": return PlatformID.HPUX; - case "AIX": return PlatformID.AIX; - case "OS400": return PlatformID.OS400; + case "DragonFly": return PlatformID.DragonFly; + case "Haiku": return PlatformID.Haiku; + case "HP-UX": return PlatformID.HPUX; + case "AIX": return PlatformID.AIX; + case "OS400": return PlatformID.OS400; case "IRIX": - case "IRIX64": return PlatformID.IRIX; + case "IRIX64": return PlatformID.IRIX; case "Minix": return PlatformID.Minix; case "NetBSD": return PlatformID.NetBSD; case "NONSTOP_KERNEL": return PlatformID.NonStop; @@ -126,63 +132,42 @@ namespace DiscImageChef.Interop case "UWIN-W7": return PlatformID.Win32NT; default: { - if(unixname.sysname.StartsWith("CYGWIN_NT", StringComparison.Ordinal) || + if(unixname.sysname.StartsWith("CYGWIN_NT", StringComparison.Ordinal) || unixname.sysname.StartsWith("MINGW32_NT", StringComparison.Ordinal) || - unixname.sysname.StartsWith("MSYS_NT", StringComparison.Ordinal) || - unixname.sysname.StartsWith("UWIN", StringComparison.Ordinal)) return PlatformID.Win32NT; + unixname.sysname.StartsWith("MSYS_NT", StringComparison.Ordinal) || + unixname.sysname.StartsWith("UWIN", StringComparison.Ordinal)) + return PlatformID.Win32NT; return PlatformID.Unknown; } } } - /// - /// Checks if the underlying runtime runs in 64-bit mode - /// - public static bool Is64Bit() - { - return IntPtr.Size == 8; - } + /// Checks if the underlying runtime runs in 64-bit mode + public static bool Is64Bit() => IntPtr.Size == 8; - /// - /// Checks if the underlying runtime runs in 32-bit mode - /// - public static bool Is32Bit() - { - return IntPtr.Size == 4; - } + /// Checks if the underlying runtime runs in 32-bit mode + public static bool Is32Bit() => IntPtr.Size == 4; - /// - /// POSIX uname structure, size from OSX, big enough to handle extra fields - /// + /// POSIX uname structure, size from OSX, big enough to handle extra fields [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] struct utsname { - /// - /// System name - /// + /// System name [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] - public string sysname; - /// - /// Node name - /// + public readonly string sysname; + /// Node name [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] - public string nodename; - /// - /// Release level - /// + public readonly string nodename; + /// Release level [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] - public string release; - /// - /// Version level - /// + public readonly string release; + /// Version level [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] - public string version; - /// - /// Hardware level - /// + public readonly string version; + /// Hardware level [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] - public string machine; + public readonly string machine; } } } \ No newline at end of file diff --git a/apprepodbmgr.Core/IO.cs b/apprepodbmgr.Core/IO.cs index f11c07c..020d82f 100644 --- a/apprepodbmgr.Core/IO.cs +++ b/apprepodbmgr.Core/IO.cs @@ -6,28 +6,32 @@ namespace apprepodbmgr.Core { public static class IO { - public static List EnumerateFiles(string path, string searchPattern, - SearchOption searchOption, - bool followLinks = true, bool symlinks = true) + public static List EnumerateFiles(string path, string searchPattern, SearchOption searchOption, + bool followLinks = true, bool symlinks = true) { - if(followLinks) return new List(Directory.EnumerateFiles(path, searchPattern, searchOption)); + if(followLinks) + return new List(Directory.EnumerateFiles(path, searchPattern, searchOption)); List files = new List(); List directories = new List(); foreach(string file in Directory.EnumerateFiles(path, searchPattern)) { - FileInfo fi = new FileInfo(file); - if(fi.Attributes.HasFlag(FileAttributes.ReparsePoint) && symlinks) files.Add(file); + var fi = new FileInfo(file); + + if(fi.Attributes.HasFlag(FileAttributes.ReparsePoint) && symlinks) + files.Add(file); else if(!fi.Attributes.HasFlag(FileAttributes.ReparsePoint)) files.Add(file); } - if(searchOption != SearchOption.AllDirectories) return files; + if(searchOption != SearchOption.AllDirectories) + return files; foreach(string directory in Directory.EnumerateDirectories(path, searchPattern)) { - DirectoryInfo di = new DirectoryInfo(directory); + var di = new DirectoryInfo(directory); + if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint)) files.AddRange(EnumerateFiles(directory, searchPattern, searchOption, followLinks, symlinks)); } @@ -35,20 +39,20 @@ namespace apprepodbmgr.Core return files; } - public static List EnumerateDirectories(string path, string searchPattern, - SearchOption searchOption, - bool followLinks = true, bool symlinks = true) + public static List EnumerateDirectories(string path, string searchPattern, SearchOption searchOption, + bool followLinks = true, bool symlinks = true) { - if(followLinks) return new List(Directory.EnumerateDirectories(path, searchPattern, searchOption)); + if(followLinks) + return new List(Directory.EnumerateDirectories(path, searchPattern, searchOption)); List directories = new List(); - if(searchOption != SearchOption.AllDirectories) return directories; + if(searchOption != SearchOption.AllDirectories) + return directories; - directories.AddRange(from directory in Directory.EnumerateDirectories(path, searchPattern) - let di = new DirectoryInfo(directory) - where !di.Attributes.HasFlag(FileAttributes.ReparsePoint) - select directory); + directories.AddRange(from directory in Directory.EnumerateDirectories(path, searchPattern) let di = + new DirectoryInfo(directory) + where !di.Attributes.HasFlag(FileAttributes.ReparsePoint) select directory); List newDirectories = new List(); @@ -65,17 +69,18 @@ namespace apprepodbmgr.Core { List directories = new List(); - List links = (from file in Directory.EnumerateFiles(path, searchPattern) - let fi = new FileInfo(file) - where fi.Attributes.HasFlag(FileAttributes.ReparsePoint) - select file).ToList(); + List links = (from file in Directory.EnumerateFiles(path, searchPattern) let fi = new FileInfo(file) + where fi.Attributes.HasFlag(FileAttributes.ReparsePoint) select file).ToList(); - if(searchOption != SearchOption.AllDirectories) return links; + if(searchOption != SearchOption.AllDirectories) + return links; foreach(string directory in Directory.EnumerateDirectories(path, searchPattern)) { - DirectoryInfo di = new DirectoryInfo(directory); - if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint)) directories.Add(directory); + var di = new DirectoryInfo(directory); + + if(!di.Attributes.HasFlag(FileAttributes.ReparsePoint)) + directories.Add(directory); else //if (!links.Contains(directory)) links.Add(directory); } diff --git a/apprepodbmgr.Core/PlatformID.cs b/apprepodbmgr.Core/PlatformID.cs index c194c02..eef9bff 100644 --- a/apprepodbmgr.Core/PlatformID.cs +++ b/apprepodbmgr.Core/PlatformID.cs @@ -40,150 +40,77 @@ namespace DiscImageChef.Interop { public enum PlatformID { - /// - /// Win32s - /// + /// Win32s Win32S = 0, - /// - /// Win32 (Windows 9x) - /// + /// Win32 (Windows 9x) Win32Windows = 1, - /// - /// Windows NT - /// + /// Windows NT Win32NT = 2, - /// - /// Windows Mobile - /// + /// Windows Mobile WinCE = 3, - /// - /// UNIX (do not use, too generic) - /// + /// UNIX (do not use, too generic) Unix = 4, - /// - /// Xbox 360 - /// + /// Xbox 360 Xbox = 5, - /// - /// OS X - /// + /// OS X MacOSX = 6, - /// - /// iOS is not OS X - /// + /// iOS is not OS X iOS = 7, - /// - /// Linux - /// + /// Linux Linux = 8, - /// - /// Sun Solaris - /// + /// Sun Solaris Solaris = 9, - /// - /// NetBSD - /// + /// NetBSD NetBSD = 10, - /// - /// OpenBSD - /// + /// OpenBSD OpenBSD = 11, - /// - /// FreeBSD - /// + /// FreeBSD FreeBSD = 12, - /// - /// DragonFly BSD - /// + /// DragonFly BSD DragonFly = 13, - /// - /// Nintendo Wii - /// + /// Nintendo Wii Wii = 14, - /// - /// Nintendo Wii U - /// + /// Nintendo Wii U WiiU = 15, - /// - /// Sony PlayStation 3 - /// + /// Sony PlayStation 3 PlayStation3 = 16, - /// - /// Sony Playstation 4 - /// + /// Sony Playstation 4 PlayStation4 = 17, - /// - /// Google Android - /// + /// Google Android Android = 18, - /// - /// Samsung Tizen - /// + /// Samsung Tizen Tizen = 19, - /// - /// Windows Phone - /// + /// Windows Phone WindowsPhone = 20, - /// - /// GNU/Hurd - /// + /// GNU/Hurd Hurd = 21, - /// - /// Haiku - /// + /// Haiku Haiku = 22, - /// - /// HP-UX - /// + /// HP-UX HPUX = 23, - /// - /// AIX - /// + /// AIX AIX = 24, - /// - /// OS/400 - /// + /// OS/400 OS400 = 25, - /// - /// IRIX - /// + /// IRIX IRIX = 26, - /// - /// Minix - /// + /// Minix Minix = 27, - /// - /// NonStop - /// + /// NonStop NonStop = 28, - /// - /// QNX - /// + /// QNX QNX = 29, - /// - /// SINIX - /// + /// SINIX SINIX = 30, - /// - /// Tru64 UNIX - /// + /// Tru64 UNIX Tru64 = 31, - /// - /// Ultrix - /// + /// Ultrix Ultrix = 32, - /// - /// SCO OpenServer / SCO UNIX - /// + /// SCO OpenServer / SCO UNIX OpenServer = 33, - /// - /// SCO UnixWare - /// + /// SCO UnixWare UnixWare = 34, - /// - /// IBM z/OS - /// - zOS = 35, - Unknown = -1 + /// IBM z/OS + zOS = 35, Unknown = -1 } } \ No newline at end of file diff --git a/apprepodbmgr.Core/PluginBase.cs b/apprepodbmgr.Core/PluginBase.cs index 7cf96c8..83a6791 100644 --- a/apprepodbmgr.Core/PluginBase.cs +++ b/apprepodbmgr.Core/PluginBase.cs @@ -40,35 +40,21 @@ using DiscImageChef.Partitions; namespace apprepodbmgr.Core { - /// - /// Contain all plugins (filesystem, partition and image) - /// + /// Contain all plugins (filesystem, partition and image) public class PluginBase { - /// - /// List of all media image plugins - /// + /// List of all media image plugins public readonly SortedDictionary ImagePluginsList; - /// - /// List of all partition plugins - /// + /// List of all partition plugins public readonly SortedDictionary PartPluginsList; - /// - /// List of all filesystem plugins - /// + /// List of all filesystem plugins public readonly SortedDictionary PluginsList; - /// - /// List of read-only filesystem plugins - /// + /// List of read-only filesystem plugins public readonly SortedDictionary ReadOnlyFilesystems; - /// - /// List of writable media image plugins - /// + /// List of writable media image plugins public readonly SortedDictionary WritableImages; - /// - /// Initializes the plugins lists - /// + /// Initializes the plugins lists public PluginBase() { PluginsList = new SortedDictionary(); @@ -77,62 +63,86 @@ namespace apprepodbmgr.Core ImagePluginsList = new SortedDictionary(); WritableImages = new SortedDictionary(); - Assembly assembly = Assembly.GetAssembly(typeof(IMediaImage)); + var assembly = Assembly.GetAssembly(typeof(IMediaImage)); - foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IMediaImage))) - .Where(t => t.IsClass)) + foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IMediaImage))). + Where(t => t.IsClass)) try { - IMediaImage plugin = (IMediaImage)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { }); + var plugin = (IMediaImage)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] + {}); + RegisterImagePlugin(plugin); } - catch(Exception exception) { Console.WriteLine("Exception {0}", exception); } + catch(Exception exception) + { + Console.WriteLine("Exception {0}", exception); + } assembly = Assembly.GetAssembly(typeof(IPartition)); - foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IPartition))) - .Where(t => t.IsClass)) + foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IPartition))). + Where(t => t.IsClass)) try { - IPartition plugin = (IPartition)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { }); + var plugin = (IPartition)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] + {}); + RegisterPartPlugin(plugin); } - catch(Exception exception) { Console.WriteLine("Exception {0}", exception); } + catch(Exception exception) + { + Console.WriteLine("Exception {0}", exception); + } assembly = Assembly.GetAssembly(typeof(IFilesystem)); - foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IFilesystem))) - .Where(t => t.IsClass)) + foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IFilesystem))). + Where(t => t.IsClass)) try { - IFilesystem plugin = (IFilesystem)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { }); + var plugin = (IFilesystem)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] + {}); + RegisterPlugin(plugin); } - catch(Exception exception) { Console.WriteLine("Exception {0}", exception); } + catch(Exception exception) + { + Console.WriteLine("Exception {0}", exception); + } assembly = Assembly.GetAssembly(typeof(IReadOnlyFilesystem)); - foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IReadOnlyFilesystem))) - .Where(t => t.IsClass)) + foreach(Type type in assembly.GetTypes(). + Where(t => t.GetInterfaces().Contains(typeof(IReadOnlyFilesystem))). + Where(t => t.IsClass)) try { - IReadOnlyFilesystem plugin = - (IReadOnlyFilesystem)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { }); + var plugin = (IReadOnlyFilesystem)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] + {}); + RegisterReadOnlyFilesystem(plugin); } - catch(Exception exception) { Console.WriteLine("Exception {0}", exception); } + catch(Exception exception) + { + Console.WriteLine("Exception {0}", exception); + } assembly = Assembly.GetAssembly(typeof(IWritableImage)); - foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IWritableImage))) - .Where(t => t.IsClass)) + foreach(Type type in assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IWritableImage))). + Where(t => t.IsClass)) try { - IWritableImage plugin = - (IWritableImage)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] { }); + var plugin = (IWritableImage)type.GetConstructor(Type.EmptyTypes)?.Invoke(new object[] + {}); + RegisterWritableMedia(plugin); } - catch(Exception exception) { Console.WriteLine("Exception {0}", exception); } + catch(Exception exception) + { + Console.WriteLine("Exception {0}", exception); + } } void RegisterImagePlugin(IMediaImage plugin) @@ -143,7 +153,8 @@ namespace apprepodbmgr.Core void RegisterPlugin(IFilesystem plugin) { - if(!PluginsList.ContainsKey(plugin.Name.ToLower())) PluginsList.Add(plugin.Name.ToLower(), plugin); + if(!PluginsList.ContainsKey(plugin.Name.ToLower())) + PluginsList.Add(plugin.Name.ToLower(), plugin); } void RegisterReadOnlyFilesystem(IReadOnlyFilesystem plugin) @@ -154,7 +165,8 @@ namespace apprepodbmgr.Core void RegisterWritableMedia(IWritableImage plugin) { - if(!WritableImages.ContainsKey(plugin.Name.ToLower())) WritableImages.Add(plugin.Name.ToLower(), plugin); + if(!WritableImages.ContainsKey(plugin.Name.ToLower())) + WritableImages.Add(plugin.Name.ToLower(), plugin); } void RegisterPartPlugin(IPartition partplugin) diff --git a/apprepodbmgr.Core/SQLite.cs b/apprepodbmgr.Core/SQLite.cs index fb6d39c..355477d 100644 --- a/apprepodbmgr.Core/SQLite.cs +++ b/apprepodbmgr.Core/SQLite.cs @@ -42,23 +42,30 @@ namespace apprepodbmgr.Core try { string dataSrc = $"URI=file:{database}"; - dbCon = new SQLiteConnection(dataSrc); + dbCon = new SQLiteConnection(dataSrc); dbCon.Open(); const string SQL = "SELECT * FROM apprepodbmgr"; - SQLiteCommand dbcmd = dbCon.CreateCommand(); - dbcmd.CommandText = SQL; - SQLiteDataAdapter dAdapter = new SQLiteDataAdapter {SelectCommand = dbcmd}; - DataSet dSet = new DataSet(); + SQLiteCommand dbcmd = dbCon.CreateCommand(); + dbcmd.CommandText = SQL; + + var dAdapter = new SQLiteDataAdapter + { + SelectCommand = dbcmd + }; + + var dSet = new DataSet(); dAdapter.Fill(dSet); DataTable dTable = dSet.Tables[0]; - if(dTable.Rows.Count != 1) return false; + if(dTable.Rows.Count != 1) + return false; if((long)dTable.Rows[0]["version"] != 1) { dbCon = null; + return false; } @@ -71,6 +78,7 @@ namespace apprepodbmgr.Core Console.WriteLine("Error opening DB."); Console.WriteLine(ex.Message); dbCon = null; + return false; } } @@ -87,37 +95,37 @@ namespace apprepodbmgr.Core try { string dataSrc = $"URI=file:{database}"; - dbCon = new SQLiteConnection(dataSrc); + dbCon = new SQLiteConnection(dataSrc); dbCon.Open(); SQLiteCommand dbCmd = dbCon.CreateCommand(); - #if DEBUG + #if DEBUG Console.WriteLine("Creating apprepodbmgr table"); - #endif + #endif - string sql = "CREATE TABLE apprepodbmgr ( version INTEGER, name TEXT )"; + string sql = "CREATE TABLE apprepodbmgr ( version INTEGER, name TEXT )"; dbCmd.CommandText = sql; dbCmd.ExecuteNonQuery(); - sql = - "INSERT INTO apprepodbmgr ( version, name ) VALUES ( '1', 'Canary Islands Computer Museum' )"; + sql = "INSERT INTO apprepodbmgr ( version, name ) VALUES ( '1', 'Canary Islands Computer Museum' )"; dbCmd.CommandText = sql; dbCmd.ExecuteNonQuery(); - #if DEBUG + #if DEBUG Console.WriteLine("Creating applications table"); - #endif + #endif dbCmd.CommandText = Schema.AppsTableSql; dbCmd.ExecuteNonQuery(); - #if DEBUG + #if DEBUG Console.WriteLine("Creating files table"); - #endif + #endif dbCmd.CommandText = Schema.FilesTableSql; dbCmd.ExecuteNonQuery(); dbCmd.Dispose(); dbCon = null; + return true; } catch(SQLiteException ex) @@ -125,14 +133,12 @@ namespace apprepodbmgr.Core Console.WriteLine("Error opening DB."); Console.WriteLine(ex.Message); dbCon = null; + return false; } } - public override IDbDataAdapter GetNewDataAdapter() - { - return new SQLiteDataAdapter(); - } + public override IDbDataAdapter GetNewDataAdapter() => new SQLiteDataAdapter(); public override long LastInsertRowId => dbCon.LastInsertRowId; #endregion diff --git a/apprepodbmgr.Core/Schema.cs b/apprepodbmgr.Core/Schema.cs index 024e885..cd9fb2c 100644 --- a/apprepodbmgr.Core/Schema.cs +++ b/apprepodbmgr.Core/Schema.cs @@ -30,57 +30,46 @@ namespace apprepodbmgr.Core { public static class Schema { - public const string FilesTableSql = "-- -----------------------------------------------------\n" + - "-- Table `files`\n" + - "-- -----------------------------------------------------\n" + - "DROP TABLE IF EXISTS `files` ;\n\n" + - "CREATE TABLE IF NOT EXISTS `files` (\n" + - " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + - " `sha256` VARCHAR(64) NOT NULL,\n" + - " `crack` BOOLEAN NOT NULL,\n" + - " `hasvirus` BOOLEAN NULL,\n" + - " `clamtime` DATETIME NULL,\n" + - " `vtotaltime` DATETIME NULL,\n" + - " `virus` VARCHAR(128) NULL,\n" + - " `length` BIGINT NOT NULL);\n\n" + - "CREATE UNIQUE INDEX `files_id_UNIQUE` ON `files` (`id` ASC);\n\n" + + public const string FilesTableSql = "-- -----------------------------------------------------\n" + + "-- Table `files`\n" + + "-- -----------------------------------------------------\n" + + "DROP TABLE IF EXISTS `files` ;\n\n" + + "CREATE TABLE IF NOT EXISTS `files` (\n" + + " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + + " `sha256` VARCHAR(64) NOT NULL,\n" + " `crack` BOOLEAN NOT NULL,\n" + + " `hasvirus` BOOLEAN NULL,\n" + " `clamtime` DATETIME NULL,\n" + + " `vtotaltime` DATETIME NULL,\n" + " `virus` VARCHAR(128) NULL,\n" + + " `length` BIGINT NOT NULL);\n\n" + + "CREATE UNIQUE INDEX `files_id_UNIQUE` ON `files` (`id` ASC);\n\n" + "CREATE UNIQUE INDEX `files_sha256_UNIQUE` ON `files` (`sha256` ASC);\n\n" + - "CREATE INDEX `files_hasvirus_idx` ON `files` (`hasvirus` ASC);\n\n" + - "CREATE INDEX `files_virus_idx` ON `files` (`virus` ASC);\n\n" + + "CREATE INDEX `files_hasvirus_idx` ON `files` (`hasvirus` ASC);\n\n" + + "CREATE INDEX `files_virus_idx` ON `files` (`virus` ASC);\n\n" + "CREATE INDEX `files_length_idx` ON `files` (`length` ASC);"; - public const string AppsTableSql = "-- -----------------------------------------------------\n" + - "-- Table `apps`\n" + - "-- -----------------------------------------------------\n" + - "DROP TABLE IF EXISTS `apps` ;\n\n" + - "CREATE TABLE IF NOT EXISTS `apps` (\n" + - " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + - " `mdid` CHAR(40) NOT NULL,\n" + - " `developer` VARCHAR(45) NOT NULL,\n" + - " `product` VARCHAR(45) NOT NULL,\n" + - " `version` VARCHAR(45) NULL,\n" + - " `languages` VARCHAR(45) NULL,\n" + - " `architecture` VARCHAR(45) NULL,\n" + - " `targetos` VARCHAR(45) NULL,\n" + - " `format` VARCHAR(45) NULL,\n" + - " `description` TEXT NULL,\n" + - " `oem` BOOLEAN NOT NULL,\n" + - " `upgrade` BOOLEAN NOT NULL,\n" + - " `update` BOOLEAN NOT NULL,\n" + - " `source` BOOLEAN NOT NULL,\n" + - " `files` BOOLEAN NOT NULL,\n" + - " `installer` BOOLEAN NOT NULL,\n" + - " `xml` BLOB NULL,\n" + - " `json` BLOB NULL,\n" + - " `icon` BLOB NULL);\n\n" + - "CREATE UNIQUE INDEX `apps_id_UNIQUE` ON `apps` (`id` ASC);\n\n" + - "CREATE UNIQUE INDEX `apps_mdid_UNIQUE` ON `apps` (`mdid` ASC);\n\n" + - "CREATE INDEX `apps_developer_idx` ON `apps` (`developer` ASC);\n\n" + - "CREATE INDEX `apps_product_idx` ON `apps` (`product` ASC);\n\n" + - "CREATE INDEX `apps_version_idx` ON `apps` (`version` ASC);\n\n" + + public const string AppsTableSql = "-- -----------------------------------------------------\n" + + "-- Table `apps`\n" + + "-- -----------------------------------------------------\n" + + "DROP TABLE IF EXISTS `apps` ;\n\n" + + "CREATE TABLE IF NOT EXISTS `apps` (\n" + + " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + + " `mdid` CHAR(40) NOT NULL,\n" + " `developer` VARCHAR(45) NOT NULL,\n" + + " `product` VARCHAR(45) NOT NULL,\n" + " `version` VARCHAR(45) NULL,\n" + + " `languages` VARCHAR(45) NULL,\n" + + " `architecture` VARCHAR(45) NULL,\n" + " `targetos` VARCHAR(45) NULL,\n" + + " `format` VARCHAR(45) NULL,\n" + " `description` TEXT NULL,\n" + + " `oem` BOOLEAN NOT NULL,\n" + " `upgrade` BOOLEAN NOT NULL,\n" + + " `update` BOOLEAN NOT NULL,\n" + " `source` BOOLEAN NOT NULL,\n" + + " `files` BOOLEAN NOT NULL,\n" + " `installer` BOOLEAN NOT NULL,\n" + + " `xml` BLOB NULL,\n" + " `json` BLOB NULL,\n" + + " `icon` BLOB NULL);\n\n" + + "CREATE UNIQUE INDEX `apps_id_UNIQUE` ON `apps` (`id` ASC);\n\n" + + "CREATE UNIQUE INDEX `apps_mdid_UNIQUE` ON `apps` (`mdid` ASC);\n\n" + + "CREATE INDEX `apps_developer_idx` ON `apps` (`developer` ASC);\n\n" + + "CREATE INDEX `apps_product_idx` ON `apps` (`product` ASC);\n\n" + + "CREATE INDEX `apps_version_idx` ON `apps` (`version` ASC);\n\n" + "CREATE INDEX `apps_architecture_idx` ON `apps` (`architecture` ASC);\n\n" + - "CREATE INDEX `apps_format_idx` ON `apps` (`format` ASC);\n\n" + - "CREATE INDEX `apps_targetos_idx` ON `apps` (`targetos` ASC);\n\n" + + "CREATE INDEX `apps_format_idx` ON `apps` (`format` ASC);\n\n" + + "CREATE INDEX `apps_targetos_idx` ON `apps` (`targetos` ASC);\n\n" + "CREATE INDEX `apps_description_idx` ON `apps` (`description` ASC);"; } } \ No newline at end of file diff --git a/apprepodbmgr.Core/Settings.cs b/apprepodbmgr.Core/Settings.cs index 2ceaee3..1ca6aa6 100644 --- a/apprepodbmgr.Core/Settings.cs +++ b/apprepodbmgr.Core/Settings.cs @@ -59,7 +59,7 @@ namespace apprepodbmgr.Core public static void LoadSettings() { - Current = new SetSettings(); + Current = new SetSettings(); PlatformID ptId = DetectOS.GetRealPlatformID(); FileStream prefsFs = null; @@ -75,6 +75,7 @@ namespace apprepodbmgr.Core string preferencesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Preferences"); + string preferencesFilePath = Path.Combine(preferencesPath, "com.claunia.museum.apprepodbmgr.plist"); @@ -84,36 +85,36 @@ namespace apprepodbmgr.Core SaveSettings(); } - prefsFs = new FileStream(preferencesFilePath, FileMode.Open); - NSDictionary parsedPreferences = (NSDictionary)BinaryPropertyListParser.Parse(prefsFs); + prefsFs = new FileStream(preferencesFilePath, FileMode.Open); + var parsedPreferences = (NSDictionary)BinaryPropertyListParser.Parse(prefsFs); + if(parsedPreferences != null) { Current.TemporaryFolder = parsedPreferences.TryGetValue("TemporaryFolder", out NSObject obj) - ? ((NSString)obj).ToString() - : Path.GetTempPath(); + ? ((NSString)obj).ToString() : Path.GetTempPath(); Current.DatabasePath = parsedPreferences.TryGetValue("DatabasePath", out obj) ? ((NSString)obj).ToString() - : Path - .Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + : Path. + Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "apprepodbmgr.db"); Current.RepositoryPath = parsedPreferences.TryGetValue("RepositoryPath", out obj) ? ((NSString)obj).ToString() - : Path - .Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + : Path. + Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "apprepo"); Current.UnArchiverPath = parsedPreferences.TryGetValue("UnArchiverPath", out obj) - ? ((NSString)obj).ToString() - : null; + ? ((NSString)obj).ToString() : null; if(parsedPreferences.TryGetValue("CompressionAlgorithm", out obj)) { if(!Enum.TryParse(((NSString)obj).ToString(), true, out Current.CompressionAlgorithm)) Current.CompressionAlgorithm = AlgoEnum.GZip; } - else Current.CompressionAlgorithm = AlgoEnum.GZip; + else + Current.CompressionAlgorithm = AlgoEnum.GZip; Current.UseAntivirus = parsedPreferences.TryGetValue("UseAntivirus", out obj) && ((NSNumber)obj).ToBool(); @@ -122,12 +123,12 @@ namespace apprepodbmgr.Core ((NSNumber)obj).ToBool(); Current.ClamdHost = parsedPreferences.TryGetValue("ClamdHost", out obj) - ? ((NSString)obj).ToString() - : null; + ? ((NSString)obj).ToString() : null; if(parsedPreferences.TryGetValue("ClamdPort", out obj)) - Current.ClamdPort = (ushort)((NSNumber)obj).ToLong(); - else Current.ClamdPort = 3310; + Current.ClamdPort = (ushort)((NSNumber)obj).ToLong(); + else + Current.ClamdPort = 3310; Current.ClamdIsLocal = parsedPreferences.TryGetValue("ClamdIsLocal", out obj) && ((NSNumber)obj).ToBool(); @@ -136,8 +137,7 @@ namespace apprepodbmgr.Core ((NSNumber)obj).ToBool(); Current.ClamdHost = parsedPreferences.TryGetValue("VirusTotalKey", out obj) - ? ((NSString)obj).ToString() - : null; + ? ((NSString)obj).ToString() : null; prefsFs.Close(); } @@ -149,6 +149,7 @@ namespace apprepodbmgr.Core SaveSettings(); } } + break; case PlatformID.Win32NT: case PlatformID.Win32S: @@ -156,21 +157,24 @@ namespace apprepodbmgr.Core case PlatformID.WinCE: case PlatformID.WindowsPhone: { - RegistryKey parentKey = Registry - .CurrentUser.OpenSubKey("SOFTWARE") - ?.OpenSubKey("Canary Islands Computer Museum"); + RegistryKey parentKey = Registry.CurrentUser.OpenSubKey("SOFTWARE")?. + OpenSubKey("Canary Islands Computer Museum"); + if(parentKey == null) { SetDefaultSettings(); SaveSettings(); + return; } RegistryKey key = parentKey.OpenSubKey("AppRepoDBMgr"); + if(key == null) { SetDefaultSettings(); SaveSettings(); + return; } @@ -178,37 +182,42 @@ namespace apprepodbmgr.Core Current.DatabasePath = (string)key.GetValue("DatabasePath"); Current.RepositoryPath = (string)key.GetValue("RepositoryPath"); Current.UnArchiverPath = (string)key.GetValue("UnArchiverPath"); + if(!Enum.TryParse((string)key.GetValue("CompressionAlgorithm"), true, out Current.CompressionAlgorithm)) Current.CompressionAlgorithm = AlgoEnum.GZip; - Current.UseAntivirus = bool.Parse((string)key.GetValue("UseAntivirus")); - Current.UseClamd = bool.Parse((string)key.GetValue("UseClamd")); - Current.ClamdHost = (string)key.GetValue("ClamdHost"); - Current.ClamdPort = ushort.Parse((string)key.GetValue("ClamdPort")); - Current.ClamdIsLocal = bool.Parse((string)key.GetValue("ClamdIsLocal")); + + Current.UseAntivirus = bool.Parse((string)key.GetValue("UseAntivirus")); + Current.UseClamd = bool.Parse((string)key.GetValue("UseClamd")); + Current.ClamdHost = (string)key.GetValue("ClamdHost"); + Current.ClamdPort = ushort.Parse((string)key.GetValue("ClamdPort")); + Current.ClamdIsLocal = bool.Parse((string)key.GetValue("ClamdIsLocal")); Current.UseVirusTotal = bool.Parse((string)key.GetValue("UseVirusTotal")); - Current.VirusTotalKey = (string)key.GetValue("VirusTotalKey"); + Current.VirusTotalKey = (string)key.GetValue("VirusTotalKey"); } + break; default: { string configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config"); - string settingsPath = - Path.Combine(configPath, "AppRepoDBMgr.xml"); + + string settingsPath = Path.Combine(configPath, "AppRepoDBMgr.xml"); if(!Directory.Exists(configPath)) { SetDefaultSettings(); SaveSettings(); + return; } - XmlSerializer xs = new XmlSerializer(Current.GetType()); - prefsSr = new StreamReader(settingsPath); - Current = (SetSettings)xs.Deserialize(prefsSr); + var xs = new XmlSerializer(Current.GetType()); + prefsSr = new StreamReader(settingsPath); + Current = (SetSettings)xs.Deserialize(prefsSr); prefsSr.Close(); } + break; } } @@ -233,32 +242,58 @@ namespace apprepodbmgr.Core case PlatformID.MacOSX: case PlatformID.iOS: { - NSDictionary root = new NSDictionary + var root = new NSDictionary { - {"TemporaryFolder", Current.TemporaryFolder}, - {"DatabasePath", Current.DatabasePath}, - {"RepositoryPath", Current.RepositoryPath}, - {"UnArchiverPath", Current.UnArchiverPath}, - {"CompressionAlgorithm", Current.CompressionAlgorithm.ToString()}, - {"UseAntivirus", Current.UseAntivirus}, - {"UseClamd", Current.UseClamd}, - {"ClamdHost", Current.ClamdHost}, - {"ClamdPort", Current.ClamdPort}, - {"ClamdIsLocal", Current.ClamdIsLocal}, - {"UseVirusTotal", Current.UseVirusTotal}, - {"VirusTotalKey", Current.VirusTotalKey} + { + "TemporaryFolder", Current.TemporaryFolder + }, + { + "DatabasePath", Current.DatabasePath + }, + { + "RepositoryPath", Current.RepositoryPath + }, + { + "UnArchiverPath", Current.UnArchiverPath + }, + { + "CompressionAlgorithm", Current.CompressionAlgorithm.ToString() + }, + { + "UseAntivirus", Current.UseAntivirus + }, + { + "UseClamd", Current.UseClamd + }, + { + "ClamdHost", Current.ClamdHost + }, + { + "ClamdPort", Current.ClamdPort + }, + { + "ClamdIsLocal", Current.ClamdIsLocal + }, + { + "UseVirusTotal", Current.UseVirusTotal + }, + { + "VirusTotalKey", Current.VirusTotalKey + } }; string preferencesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Preferences"); + string preferencesFilePath = Path.Combine(preferencesPath, "com.claunia.museum.apprepodbmgr.plist"); - FileStream fs = new FileStream(preferencesFilePath, FileMode.Create); + var fs = new FileStream(preferencesFilePath, FileMode.Create); BinaryPropertyListWriter.Write(fs, root); fs.Close(); } + break; case PlatformID.Win32NT: case PlatformID.Win32S: @@ -266,43 +301,48 @@ namespace apprepodbmgr.Core case PlatformID.WinCE: case PlatformID.WindowsPhone: { - RegistryKey parentKey = Registry - .CurrentUser.OpenSubKey("SOFTWARE", true) - ?.CreateSubKey("Canary Islands Computer Museum"); + RegistryKey parentKey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true)?. + CreateSubKey("Canary Islands Computer Museum"); + RegistryKey key = parentKey?.CreateSubKey("AppRepoDBMgr"); if(key != null) { - key.SetValue("TemporaryFolder", Current.TemporaryFolder); - key.SetValue("DatabasePath", Current.DatabasePath); - key.SetValue("RepositoryPath", Current.RepositoryPath); - if(Current.UnArchiverPath != null) key.SetValue("UnArchiverPath", Current.UnArchiverPath); - key.SetValue("CompressionAlgorithm", - Current.CompressionAlgorithm); - key.SetValue("UseAntivirus", Current.UseAntivirus); - key.SetValue("UseClamd", Current.UseClamd); - key.SetValue("ClamdHost", Current.ClamdHost == null ? "" : Current.ClamdHost); - key.SetValue("ClamdPort", Current.ClamdPort); - key.SetValue("ClamdIsLocal", Current.ClamdIsLocal); + key.SetValue("TemporaryFolder", Current.TemporaryFolder); + key.SetValue("DatabasePath", Current.DatabasePath); + key.SetValue("RepositoryPath", Current.RepositoryPath); + + if(Current.UnArchiverPath != null) + key.SetValue("UnArchiverPath", Current.UnArchiverPath); + + key.SetValue("CompressionAlgorithm", Current.CompressionAlgorithm); + key.SetValue("UseAntivirus", Current.UseAntivirus); + key.SetValue("UseClamd", Current.UseClamd); + key.SetValue("ClamdHost", Current.ClamdHost == null ? "" : Current.ClamdHost); + key.SetValue("ClamdPort", Current.ClamdPort); + key.SetValue("ClamdIsLocal", Current.ClamdIsLocal); key.SetValue("UseVirusTotal", Current.UseVirusTotal); key.SetValue("VirusTotalKey", Current.VirusTotalKey == null ? "" : Current.VirusTotalKey); } } + break; default: { string configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config"); - string settingsPath = - Path.Combine(configPath, "AppRepoDBMgr.xml"); - if(!Directory.Exists(configPath)) Directory.CreateDirectory(configPath); + string settingsPath = Path.Combine(configPath, "AppRepoDBMgr.xml"); - FileStream fs = new FileStream(settingsPath, FileMode.Create); - XmlSerializer xs = new XmlSerializer(Current.GetType()); + if(!Directory.Exists(configPath)) + Directory.CreateDirectory(configPath); + + var fs = new FileStream(settingsPath, FileMode.Create); + var xs = new XmlSerializer(Current.GetType()); xs.Serialize(fs, Current); fs.Close(); } + break; } } @@ -310,29 +350,26 @@ namespace apprepodbmgr.Core catch #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; } } - static void SetDefaultSettings() + static void SetDefaultSettings() => Current = new SetSettings { - Current = new SetSettings - { - TemporaryFolder = Path.GetTempPath(), - DatabasePath = - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "apprepodbmgr.db"), - RepositoryPath = - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "apprepo"), - UnArchiverPath = null, - CompressionAlgorithm = AlgoEnum.GZip, - UseAntivirus = false, - UseClamd = false, - ClamdHost = null, - ClamdPort = 3310, - ClamdIsLocal = false, - UseVirusTotal = false, - VirusTotalKey = null - }; - } + TemporaryFolder = Path.GetTempPath(), + DatabasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + "apprepodbmgr.db"), + RepositoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "apprepo"), + UnArchiverPath = null, + CompressionAlgorithm = AlgoEnum.GZip, + UseAntivirus = false, + UseClamd = false, + ClamdHost = null, + ClamdPort = 3310, + ClamdIsLocal = false, + UseVirusTotal = false, + VirusTotalKey = null + }; } } \ No newline at end of file diff --git a/apprepodbmgr.Core/Symlinks.cs b/apprepodbmgr.Core/Symlinks.cs index 98e1941..70add4b 100644 --- a/apprepodbmgr.Core/Symlinks.cs +++ b/apprepodbmgr.Core/Symlinks.cs @@ -15,7 +15,8 @@ namespace apprepodbmgr.Core int ret = readlink(path, buf, 16384); - if(ret < 0) return null; + if(ret < 0) + return null; byte[] target = new byte[ret]; Marshal.Copy(buf, target, 0, ret); @@ -26,9 +27,6 @@ namespace apprepodbmgr.Core [DllImport("libc", CharSet = CharSet.Ansi, SetLastError = true)] static extern int symlink(string target, string path); - public static int Symlink(string target, string path) - { - return symlink(target, path); - } + public static int Symlink(string target, string path) => symlink(target, path); } } \ No newline at end of file diff --git a/apprepodbmgr.Core/Workers/Clamd.cs b/apprepodbmgr.Core/Workers/Clamd.cs index b49c2f4..03670a3 100644 --- a/apprepodbmgr.Core/Workers/Clamd.cs +++ b/apprepodbmgr.Core/Workers/Clamd.cs @@ -46,27 +46,26 @@ namespace apprepodbmgr.Core public static void InitClamd() { - if(!Settings.Current.UseClamd || !Settings.Current.UseAntivirus) + if(!Settings.Current.UseClamd || + !Settings.Current.UseAntivirus) { Context.ClamdVersion = null; + return; } TestClamd(); } - public static void TestClamd() + public static void TestClamd() => Task.Run(async () => { - Task.Run(async () => + try { - try - { - clam = new ClamClient(Settings.Current.ClamdHost, Settings.Current.ClamdPort); - Context.ClamdVersion = await clam.GetVersionAsync(); - } - catch(SocketException) { } - }).Wait(); - } + clam = new ClamClient(Settings.Current.ClamdHost, Settings.Current.ClamdPort); + Context.ClamdVersion = await clam.GetVersionAsync(); + } + catch(SocketException) {} + }).Wait(); public static void ClamScanFileFromRepo(DbFile file) { @@ -75,10 +74,12 @@ namespace apprepodbmgr.Core if(Context.ClamdVersion == null) { Failed?.Invoke("clamd is not usable"); + return; } - if(clam == null) Failed?.Invoke("clamd is not initalized"); + if(clam == null) + Failed?.Invoke("clamd is not initalized"); string repoPath; AlgoEnum algorithm; @@ -90,6 +91,7 @@ namespace apprepodbmgr.Core repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".gz"); + algorithm = AlgoEnum.GZip; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -100,6 +102,7 @@ namespace apprepodbmgr.Core repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".bz2"); + algorithm = AlgoEnum.BZip2; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -111,6 +114,7 @@ namespace apprepodbmgr.Core file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lzma"); + algorithm = AlgoEnum.LZMA; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -121,11 +125,13 @@ namespace apprepodbmgr.Core repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lz"); + algorithm = AlgoEnum.LZip; } else { Failed?.Invoke($"Cannot find file with hash {file.Sha256} in the repository"); + return; } @@ -133,11 +139,12 @@ namespace apprepodbmgr.Core Stream zStream = null; if(Settings.Current.ClamdIsLocal) - if(algorithm == AlgoEnum.LZMA || algorithm == AlgoEnum.LZip) + if(algorithm == AlgoEnum.LZMA || + algorithm == AlgoEnum.LZip) { - string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName()); - FileStream outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); - FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); + string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName()); + var outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); + var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); if(algorithm == AlgoEnum.LZMA) { @@ -146,34 +153,39 @@ namespace apprepodbmgr.Core inFs.Seek(8, SeekOrigin.Current); zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length); } - else zStream = new LZipStream(inFs, CompressionMode.Decompress); + else + zStream = new LZipStream(inFs, CompressionMode.Decompress); UpdateProgress?.Invoke("Uncompressing file...", null, 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif zStream.CopyTo(outFs); zStream.Close(); outFs.Close(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.ClamScanFileFromRepo({0}): Uncompressing took {1} seconds", file, stopwatch.Elapsed.TotalSeconds); - #endif + #endif UpdateProgress?.Invoke("Requesting local scan to clamd server...", null, 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif - Task.Run(async () => { result = await clam.ScanFileOnServerMultithreadedAsync(tmpFile); }) - .Wait(); - #if DEBUG + #endif + Task.Run(async () => + { + result = await clam.ScanFileOnServerMultithreadedAsync(tmpFile); + }).Wait(); + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file, stopwatch.Elapsed.TotalSeconds); - #endif + #endif File.Delete(tmpFile); } @@ -181,55 +193,67 @@ namespace apprepodbmgr.Core { UpdateProgress?.Invoke("Requesting local scan to clamd server...", null, 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif - Task.Run(async () => { result = await clam.ScanFileOnServerMultithreadedAsync(repoPath); }) - .Wait(); - #if DEBUG + #endif + Task.Run(async () => + { + result = await clam.ScanFileOnServerMultithreadedAsync(repoPath); + }).Wait(); + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file, stopwatch.Elapsed.TotalSeconds); - #endif + #endif } else { - FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); + var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); switch(algorithm) { case AlgoEnum.GZip: zStream = new GZipStream(inFs, CompressionMode.Decompress); + break; case AlgoEnum.BZip2: zStream = new BZip2Stream(inFs, CompressionMode.Decompress); + break; case AlgoEnum.LZMA: byte[] properties = new byte[5]; inFs.Read(properties, 0, 5); inFs.Seek(8, SeekOrigin.Current); zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length); + break; case AlgoEnum.LZip: zStream = new LZipStream(inFs, CompressionMode.Decompress); + break; } UpdateProgress?.Invoke("Uploading file to clamd server...", null, 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif - Task.Run(async () => { result = await clam.SendAndScanFileAsync(zStream); }).Wait(); - #if DEBUG + #endif + Task.Run(async () => + { + result = await clam.SendAndScanFileAsync(zStream); + }).Wait(); + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.ClamScanFileFromRepo({0}): Clamd took {1} seconds to scan", file, stopwatch.Elapsed.TotalSeconds); - #endif + #endif zStream.Close(); } - if(result.InfectedFiles != null && result.InfectedFiles.Count > 0) + if(result.InfectedFiles != null && + result.InfectedFiles.Count > 0) { file.HasVirus = true; file.Virus = result.InfectedFiles[0].VirusName; @@ -248,13 +272,13 @@ namespace apprepodbmgr.Core ScanFinished?.Invoke(file); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { Failed?.Invoke($"Exception {ex.Message} when calling clamd"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -262,19 +286,22 @@ namespace apprepodbmgr.Core { UpdateProgress2?.Invoke("Asking database for files", null, 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif if(!dbCore.DbOps.GetNotAvFiles(out List files)) Failed?.Invoke("Could not get files from database."); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds to get files from database", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif int counter = 0; + foreach(DbFile file in files) { UpdateProgress2?.Invoke($"Scanning file {counter} of {files.Count}", null, counter, files.Count); @@ -283,11 +310,12 @@ namespace apprepodbmgr.Core counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds scan all pending files", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished?.Invoke(); } diff --git a/apprepodbmgr.Core/Workers/Compression.cs b/apprepodbmgr.Core/Workers/Compression.cs index 60397c8..d0b691b 100644 --- a/apprepodbmgr.Core/Workers/Compression.cs +++ b/apprepodbmgr.Core/Workers/Compression.cs @@ -53,18 +53,21 @@ namespace apprepodbmgr.Core if(string.IsNullOrWhiteSpace(Context.DbInfo.Developer)) { Failed?.Invoke("Developer cannot be empty"); + return; } if(string.IsNullOrWhiteSpace(Context.DbInfo.Product)) { Failed?.Invoke("Product cannot be empty"); + return; } if(string.IsNullOrWhiteSpace(Context.DbInfo.Version)) { Failed?.Invoke("Version cannot be empty"); + return; } @@ -72,53 +75,73 @@ namespace apprepodbmgr.Core destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Developer; destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Product; destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Version; + if(!string.IsNullOrWhiteSpace(Context.DbInfo.Languages)) destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Languages; + if(!string.IsNullOrWhiteSpace(Context.DbInfo.Architecture)) destinationFolder += Path.DirectorySeparatorChar + Context.DbInfo.Architecture; - if(Context.DbInfo.Oem) destinationFolder += Path.DirectorySeparatorChar + "oem"; + + if(Context.DbInfo.Oem) + destinationFolder += Path.DirectorySeparatorChar + "oem"; + if(!string.IsNullOrWhiteSpace(Context.DbInfo.TargetOs)) destinationFolder += Path.DirectorySeparatorChar + "for " + Context.DbInfo.TargetOs; string destinationFile = ""; + if(!string.IsNullOrWhiteSpace(Context.DbInfo.Format)) destinationFile += "[" + Context.DbInfo.Format + "]"; + if(Context.DbInfo.Files) { - if(destinationFile != "") destinationFile += "_"; + if(destinationFile != "") + destinationFile += "_"; + destinationFile += "files"; } if(Context.DbInfo.Installer) { - if(destinationFile != "") destinationFile += "_"; + if(destinationFile != "") + destinationFile += "_"; + destinationFile += "installer"; } if(Context.DbInfo.Source) { - if(destinationFile != "") destinationFile += "_"; + if(destinationFile != "") + destinationFile += "_"; + destinationFile += "source"; } if(Context.DbInfo.Update) { - if(destinationFile != "") destinationFile += "_"; + if(destinationFile != "") + destinationFile += "_"; + destinationFile += "update"; } if(Context.DbInfo.Upgrade) { - if(destinationFile != "") destinationFile += "_"; + if(destinationFile != "") + destinationFile += "_"; + destinationFile += "upgrade"; } if(!string.IsNullOrWhiteSpace(Context.DbInfo.Description)) { - if(destinationFile != "") destinationFile += "_"; + if(destinationFile != "") + destinationFile += "_"; + destinationFile += Context.DbInfo.Description; } - else if(destinationFile == "") destinationFile = "archive"; + else if(destinationFile == "") + destinationFile = "archive"; string destination = destinationFolder + Path.DirectorySeparatorChar + destinationFile + ".zip"; @@ -130,16 +153,19 @@ namespace apprepodbmgr.Core if(File.Exists(destination)) { Failed?.Invoke("Application already exists."); + return; } Failed?.Invoke("Application already exists in the database but not in the repository, check for inconsistencies."); + return; } if(File.Exists(destination)) { Failed?.Invoke("Application already exists in the repository but not in the database, check for inconsistencies."); + return; } @@ -147,9 +173,11 @@ namespace apprepodbmgr.Core string filesPath; - if(!string.IsNullOrEmpty(Context.TmpFolder) && Directory.Exists(Context.TmpFolder)) - filesPath = Context.TmpFolder; - else filesPath = Context.Path; + if(!string.IsNullOrEmpty(Context.TmpFolder) && + Directory.Exists(Context.TmpFolder)) + filesPath = Context.TmpFolder; + else + filesPath = Context.Path; string extension = null; @@ -157,24 +185,30 @@ namespace apprepodbmgr.Core { case AlgoEnum.GZip: extension = ".gz"; + break; case AlgoEnum.BZip2: extension = ".bz2"; + break; case AlgoEnum.LZMA: extension = ".lzma"; + break; case AlgoEnum.LZip: extension = ".lz"; + break; } - long totalSize = 0, currentSize = 0; - foreach(KeyValuePair file in Context.Hashes) totalSize += file.Value.Length; + long totalSize = 0, currentSize = 0; - #if DEBUG + foreach(KeyValuePair file in Context.Hashes) + totalSize += file.Value.Length; + + #if DEBUG stopwatch.Restart(); - #endif + #endif foreach(KeyValuePair file in Context.Hashes) { UpdateProgress?.Invoke("Compressing...", file.Value.Path, currentSize, totalSize); @@ -182,34 +216,42 @@ namespace apprepodbmgr.Core destinationFolder = Path.Combine(Settings.Current.RepositoryPath, file.Value.Sha256[0].ToString(), file.Value.Sha256[1].ToString(), file.Value.Sha256[2].ToString(), file.Value.Sha256[3].ToString(), file.Value.Sha256[4].ToString()); + Directory.CreateDirectory(destinationFolder); destinationFile = Path.Combine(destinationFolder, file.Value.Sha256 + extension); if(!File.Exists(destinationFile)) { - FileStream inFs = new FileStream(Path.Combine(filesPath, file.Value.Path), FileMode.Open, - FileAccess.Read); - FileStream outFs = new FileStream(destinationFile, FileMode.CreateNew, FileAccess.Write); - Stream zStream = null; + var inFs = new FileStream(Path.Combine(filesPath, file.Value.Path), FileMode.Open, + FileAccess.Read); + + var outFs = new FileStream(destinationFile, FileMode.CreateNew, FileAccess.Write); + Stream zStream = null; switch(Settings.Current.CompressionAlgorithm) { case AlgoEnum.GZip: zStream = new GZipStream(outFs, CompressionMode.Compress, CompressionLevel.BestCompression); + break; case AlgoEnum.BZip2: zStream = new BZip2Stream(outFs, CompressionMode.Compress); + break; case AlgoEnum.LZMA: zStream = new LzmaStream(new LzmaEncoderProperties(), false, outFs); + outFs.Write(((LzmaStream)zStream).Properties, 0, ((LzmaStream)zStream).Properties.Length); + outFs.Write(BitConverter.GetBytes(inFs.Length), 0, 8); + break; case AlgoEnum.LZip: zStream = new LZipStream(outFs, CompressionMode.Compress); + break; } @@ -220,6 +262,7 @@ namespace apprepodbmgr.Core UpdateProgress2?.Invoke($"{inFs.Position / (double)inFs.Length:P}", $"{inFs.Position} / {inFs.Length} bytes", inFs.Position, inFs.Length); + UpdateProgress?.Invoke("Compressing...", file.Value.Path, currentSize, totalSize); inFs.Read(buffer, 0, buffer.Length); @@ -228,8 +271,10 @@ namespace apprepodbmgr.Core } buffer = new byte[inFs.Length - inFs.Position]; + UpdateProgress2?.Invoke($"{inFs.Position / (double)inFs.Length:P}", $"{inFs.Position} / {inFs.Length} bytes", inFs.Position, inFs.Length); + UpdateProgress?.Invoke("Compressing...", file.Value.Path, currentSize, totalSize); inFs.Read(buffer, 0, buffer.Length); @@ -243,28 +288,31 @@ namespace apprepodbmgr.Core zStream.Close(); outFs.Dispose(); } - else currentSize += file.Value.Length; + else + currentSize += file.Value.Length; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CompressFiles(): Took {0} seconds to compress files", stopwatch.Elapsed.TotalSeconds); - #endif + #endif if(Context.Metadata != null) { - MemoryStream xms = new MemoryStream(); - XmlSerializer xs = new XmlSerializer(typeof(CICMMetadataType)); + var xms = new MemoryStream(); + var xs = new XmlSerializer(typeof(CICMMetadataType)); xs.Serialize(xms, Context.Metadata); xms.Position = 0; - JsonSerializer js = new JsonSerializer + var js = new JsonSerializer { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }; - MemoryStream jms = new MemoryStream(); - StreamWriter sw = new StreamWriter(jms, Encoding.UTF8, 1048576, true); + + var jms = new MemoryStream(); + var sw = new StreamWriter(jms, Encoding.UTF8, 1048576, true); js.Serialize(sw, Context.Metadata, typeof(CICMMetadataType)); sw.Close(); jms.Position = 0; @@ -272,14 +320,18 @@ namespace apprepodbmgr.Core destinationFolder = Path.Combine(Settings.Current.RepositoryPath, "metadata", mdid[0].ToString(), mdid[1].ToString(), mdid[2].ToString(), mdid[3].ToString(), mdid[4].ToString()); + Directory.CreateDirectory(destinationFolder); - FileStream xfs = new FileStream(Path.Combine(destinationFolder, mdid + ".xml"), FileMode.CreateNew, - FileAccess.Write); + var xfs = new FileStream(Path.Combine(destinationFolder, mdid + ".xml"), FileMode.CreateNew, + FileAccess.Write); + xms.CopyTo(xfs); xfs.Close(); - FileStream jfs = new FileStream(Path.Combine(destinationFolder, mdid + ".json"), FileMode.CreateNew, - FileAccess.Write); + + var jfs = new FileStream(Path.Combine(destinationFolder, mdid + ".json"), FileMode.CreateNew, + FileAccess.Write); + jms.CopyTo(jfs); jfs.Close(); @@ -289,15 +341,16 @@ namespace apprepodbmgr.Core FinishedWithText?.Invoke($"Correctly added application with MDID {mdid}"); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -306,12 +359,14 @@ namespace apprepodbmgr.Core if(!Context.UnarUsable) { Failed?.Invoke("The UnArchiver is not correctly installed"); + return; } if(!File.Exists(Context.Path)) { Failed?.Invoke("Specified file cannot be found"); + return; } @@ -323,10 +378,10 @@ namespace apprepodbmgr.Core string lsarfilename = unarfilename?.Replace("unar", "lsar"); string lsarPath = Path.Combine(unarFolder, lsarfilename + extension); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif - Process lsarProcess = new Process + #endif + var lsarProcess = new Process { StartInfo = { @@ -337,37 +392,46 @@ namespace apprepodbmgr.Core Arguments = $"-j \"\"\"{Context.Path}\"\"\"" } }; + lsarProcess.Start(); string lsarOutput = lsarProcess.StandardOutput.ReadToEnd(); lsarProcess.WaitForExit(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.OpenArchive(): Took {0} seconds to list archive contents", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif - long counter = 0; - string format = null; - JsonTextReader jsReader = new JsonTextReader(new StringReader(lsarOutput)); + #endif + long counter = 0; + string format = null; + var jsReader = new JsonTextReader(new StringReader(lsarOutput)); + while(jsReader.Read()) switch(jsReader.TokenType) { case JsonToken.PropertyName when jsReader.Value != null && jsReader.Value.ToString() == "XADFileName": counter++; + break; case JsonToken.PropertyName when jsReader.Value != null && jsReader.Value.ToString() == "lsarFormatName": jsReader.Read(); - if(jsReader.TokenType == JsonToken.String && jsReader.Value != null) + + if(jsReader.TokenType == JsonToken.String && + jsReader.Value != null) format = jsReader.Value.ToString(); + break; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.OpenArchive(): Took {0} seconds to process archive contents", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Context.UnzipWithUnAr = false; Context.ArchiveFormat = format; @@ -376,12 +440,14 @@ namespace apprepodbmgr.Core if(string.IsNullOrEmpty(format)) { Failed?.Invoke("File not recognized as an archive"); + return; } if(counter == 0) { Failed?.Invoke("Archive contains no files"); + return; } @@ -391,37 +457,46 @@ namespace apprepodbmgr.Core if(Context.UsableDotNetZip) { - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif - ZipFile zf = ZipFile.Read(Context.Path, new ReadOptions {Encoding = Encoding.UTF8}); + #endif + var zf = ZipFile.Read(Context.Path, new ReadOptions + { + Encoding = Encoding.UTF8 + }); + foreach(ZipEntry ze in zf) { // ZIP created with Mac OS X, need to be extracted with The UnArchiver to get correct ResourceFork structure - if(!ze.FileName.StartsWith("__MACOSX", StringComparison.CurrentCulture)) continue; + if(!ze.FileName.StartsWith("__MACOSX", StringComparison.CurrentCulture)) + continue; Context.UnzipWithUnAr = true; + break; } - #if DEBUG + #if DEBUG stopwatch.Stop(); - Console.WriteLine("Core.OpenArchive(): Took {0} seconds to navigate in search of Mac OS X metadata", - stopwatch.Elapsed.TotalSeconds); - #endif + + Console. + WriteLine("Core.OpenArchive(): Took {0} seconds to navigate in search of Mac OS X metadata", + stopwatch.Elapsed.TotalSeconds); + #endif } } Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -430,17 +505,18 @@ namespace apprepodbmgr.Core if(!File.Exists(Context.Path)) { Failed?.Invoke("Specified file cannot be found"); + return; } if(!Directory.Exists(Settings.Current.TemporaryFolder)) { Failed?.Invoke("Temporary folder cannot be found"); + return; } - string tmpFolder = Context.UserExtracting - ? Context.TmpFolder + string tmpFolder = Context.UserExtracting ? Context.TmpFolder : Path.Combine(Settings.Current.TemporaryFolder, Path.GetRandomFileName()); try @@ -449,10 +525,11 @@ namespace apprepodbmgr.Core Context.TmpFolder = tmpFolder; } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke("Cannot create temporary folder"); } @@ -460,105 +537,125 @@ namespace apprepodbmgr.Core try { // If it's a ZIP file not created by Mac OS X, use DotNetZip to uncompress (unar freaks out or corrupts certain ZIP features) - if(Context.ArchiveFormat == "Zip" && !Context.UnzipWithUnAr && Context.UsableDotNetZip) + if(Context.ArchiveFormat == "Zip" && + !Context.UnzipWithUnAr && + Context.UsableDotNetZip) try { - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif - ZipFile zf = ZipFile.Read(Context.Path, new ReadOptions {Encoding = Encoding.UTF8}); + #endif + var zf = ZipFile.Read(Context.Path, new ReadOptions + { + Encoding = Encoding.UTF8 + }); + zf.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently; zf.ExtractProgress += Zf_ExtractProgress; zipCounter = 0; zipCurrentEntryName = ""; zf.ExtractAll(tmpFolder); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } else { if(!Context.UnarUsable) { Failed?.Invoke("The UnArchiver is not correctly installed"); + return; } - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif Context.UnarProcess = new Process { StartInfo = { - FileName = Settings.Current.UnArchiverPath, - CreateNoWindow = true, + FileName = Settings.Current.UnArchiverPath, + CreateNoWindow = true, RedirectStandardOutput = true, - UseShellExecute = false, - Arguments = - $"-o \"\"\"{tmpFolder}\"\"\" -r -D -k hidden \"\"\"{Context.Path}\"\"\"" + UseShellExecute = false, + Arguments = $"-o \"\"\"{tmpFolder}\"\"\" -r -D -k hidden \"\"\"{Context.Path}\"\"\"" } }; + long counter = 0; + Context.UnarProcess.OutputDataReceived += (sender, e) => { counter++; UpdateProgress2?.Invoke("", e.Data, counter, Context.NoFilesInArchive); }; + Context.UnarProcess.Start(); Context.UnarProcess.BeginOutputReadLine(); Context.UnarProcess.WaitForExit(); Context.UnarProcess.Close(); Context.UnarProcess = null; - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.ExtractArchive(): Took {0} seconds to extract archive contents using UnAr", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished?.Invoke(); } } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } static void Zf_ExtractProgress(object sender, ExtractProgressEventArgs e) { - if(e.CurrentEntry != null && e.CurrentEntry.FileName != zipCurrentEntryName) + if(e.CurrentEntry != null && + e.CurrentEntry.FileName != zipCurrentEntryName) { zipCurrentEntryName = e.CurrentEntry.FileName; zipCounter++; } - if(UpdateProgress != null && e.CurrentEntry != null && e.EntriesTotal > 0) + if(UpdateProgress != null && + e.CurrentEntry != null && + e.EntriesTotal > 0) UpdateProgress("Extracting...", e.CurrentEntry.FileName, zipCounter, e.EntriesTotal); - if(UpdateProgress2 != null && e.TotalBytesToTransfer > 0) + + if(UpdateProgress2 != null && + e.TotalBytesToTransfer > 0) UpdateProgress2($"{e.BytesTransferred / (double)e.TotalBytesToTransfer:P}", $"{e.BytesTransferred} / {e.TotalBytesToTransfer}", e.BytesTransferred, e.TotalBytesToTransfer); - if(e.EventType != ZipProgressEventType.Extracting_AfterExtractAll || Finished == null) return; - #if DEBUG + if(e.EventType != ZipProgressEventType.Extracting_AfterExtractAll || + Finished == null) + return; + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.Zf_ExtractProgress(): Took {0} seconds to extract archive contents using DotNetZip", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished(); } @@ -569,34 +666,39 @@ namespace apprepodbmgr.Core if(string.IsNullOrWhiteSpace(Context.Path)) { Failed?.Invoke("Destination cannot be empty"); + return; } if(Directory.Exists(Context.Path)) { Failed?.Invoke("Destination cannot be a folder"); + return; } if(Context.DbInfo.Id == 0) { Failed?.Invoke("Operating system must be set"); + return; } if(dbCore.DbOps.HasSymlinks(Context.DbInfo.Id)) { Failed?.Invoke("Cannot create symbolic links on ZIP files"); + return; } if(!Context.UsableDotNetZip) { Failed?.Invoke("Cannot create ZIP files"); + return; } - ZipFile zf = new ZipFile(Context.Path, Encoding.UTF8) + var zf = new ZipFile(Context.Path, Encoding.UTF8) { CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression, CompressionMethod = CompressionMethod.Deflate, @@ -605,6 +707,7 @@ namespace apprepodbmgr.Core UseZip64WhenSaving = Zip64Option.AsNecessary, SortEntriesBeforeSaving = true }; + zf.SaveProgress += Zf_SaveProgress; UpdateProgress?.Invoke("", "Asking DB for files...", 1, 100); @@ -617,10 +720,11 @@ namespace apprepodbmgr.Core UpdateProgress?.Invoke("", "Creating folders...", 3, 100); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif long counter = 0; + foreach(DbFolder folder in folders) { UpdateProgress2?.Invoke("", folder.Path, counter, folders.Count); @@ -634,17 +738,18 @@ namespace apprepodbmgr.Core counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CompressTo(): Took {0} seconds to add folders to ZIP", stopwatch.Elapsed.TotalSeconds); - #endif + #endif counter = 3; Context.Hashes = new Dictionary(); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif foreach(DbAppFile file in files) { UpdateProgress?.Invoke("", $"Adding {file.Path}...", counter, 3 + files.Count); @@ -660,37 +765,42 @@ namespace apprepodbmgr.Core counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CompressTo(): Took {0} seconds to add files to ZIP", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif zipCounter = 0; zipCurrentEntryName = ""; zf.Save(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } static Stream Zf_HandleOpen(string entryName) { DbAppFile file; + if(!Context.Hashes.TryGetValue(entryName, out file)) if(!Context.Hashes.TryGetValue(entryName.Replace('/', '\\'), out file)) throw new ArgumentException("Cannot find requested zip entry in hashes dictionary"); // Special case for empty file, as it seems to crash when SharpCompress tries to unLZMA it. - if(file.Length == 0) return new MemoryStream(); + if(file.Length == 0) + return new MemoryStream(); Stream zStream = null; string repoPath; @@ -703,6 +813,7 @@ namespace apprepodbmgr.Core repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".gz"); + algorithm = AlgoEnum.GZip; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -713,6 +824,7 @@ namespace apprepodbmgr.Core repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".bz2"); + algorithm = AlgoEnum.BZip2; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -723,6 +835,7 @@ namespace apprepodbmgr.Core repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lzma"); + algorithm = AlgoEnum.LZMA; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -733,50 +846,58 @@ namespace apprepodbmgr.Core repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lz"); + algorithm = AlgoEnum.LZip; } - else throw new ArgumentException($"Cannot find file with hash {file.Sha256} in the repository"); + else + throw new ArgumentException($"Cannot find file with hash {file.Sha256} in the repository"); - FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); + var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); switch(algorithm) { case AlgoEnum.GZip: zStream = new GZipStream(inFs, CompressionMode.Decompress); + break; case AlgoEnum.BZip2: zStream = new BZip2Stream(inFs, CompressionMode.Decompress); + break; case AlgoEnum.LZMA: byte[] properties = new byte[5]; inFs.Read(properties, 0, 5); inFs.Seek(8, SeekOrigin.Current); zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length); + break; case AlgoEnum.LZip: zStream = new LZipStream(inFs, CompressionMode.Decompress); + break; } return zStream; } - static void Zf_HandleClose(string entryName, Stream stream) - { - stream.Close(); - } + static void Zf_HandleClose(string entryName, Stream stream) => stream.Close(); static void Zf_SaveProgress(object sender, SaveProgressEventArgs e) { - if(e.CurrentEntry != null && e.CurrentEntry.FileName != zipCurrentEntryName) + if(e.CurrentEntry != null && + e.CurrentEntry.FileName != zipCurrentEntryName) { zipCurrentEntryName = e.CurrentEntry.FileName; zipCounter++; } - if(UpdateProgress != null && e.CurrentEntry != null && e.EntriesTotal > 0) + if(UpdateProgress != null && + e.CurrentEntry != null && + e.EntriesTotal > 0) UpdateProgress("Compressing...", e.CurrentEntry.FileName, zipCounter, e.EntriesTotal); - if(UpdateProgress2 != null && e.TotalBytesToTransfer > 0) + + if(UpdateProgress2 != null && + e.TotalBytesToTransfer > 0) UpdateProgress2($"{e.BytesTransferred / (double)e.TotalBytesToTransfer:P}", $"{e.BytesTransferred} / {e.TotalBytesToTransfer}", e.BytesTransferred, e.TotalBytesToTransfer); @@ -785,14 +906,17 @@ namespace apprepodbmgr.Core { case ZipProgressEventType.Error_Saving: Failed?.Invoke("An error occurred creating ZIP file."); + break; case ZipProgressEventType.Saving_Completed when Finished != null: - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.Zf_SaveProgress(): Took {0} seconds to compress files to ZIP", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished(); + break; } } diff --git a/apprepodbmgr.Core/Workers/Database.cs b/apprepodbmgr.Core/Workers/Database.cs index cff7abf..519f593 100644 --- a/apprepodbmgr.Core/Workers/Database.cs +++ b/apprepodbmgr.Core/Workers/Database.cs @@ -40,49 +40,54 @@ namespace apprepodbmgr.Core { try { - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif dbCore.DbOps.GetAllApps(out List apps); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.GetAllApps(): Took {0} seconds to get apps from database", stopwatch.Elapsed.TotalSeconds); - #endif + #endif if(AddApp != null) { - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif int counter = 0; + // TODO: Check file name and existence foreach(DbEntry app in apps) { UpdateProgress?.Invoke("Populating apps table", $"{app.Developer} {app.Product}", counter, apps.Count); + AddApp?.Invoke(app); counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.GetAllApps(): Took {0} seconds to add apps to the GUI", stopwatch.Elapsed.TotalSeconds); - #endif + #endif } Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -91,9 +96,9 @@ namespace apprepodbmgr.Core try { long counter = 0; - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif Dictionary knownFiles = new Dictionary(); bool unknownFile = false; @@ -105,6 +110,7 @@ namespace apprepodbmgr.Core { AddFileForApp(kvp.Key, kvp.Value.Sha256, true, kvp.Value.Crack); counter++; + continue; } @@ -118,43 +124,50 @@ namespace apprepodbmgr.Core counter++; knownFiles.Add(kvp.Key, kvp.Value); } - else unknownFile = true; + else + unknownFile = true; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds to checks for file knowledge in the DB", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif if(knownFiles.Count == 0 || unknownFile) { Finished?.Invoke(); + return; } UpdateProgress?.Invoke(null, "Retrieving apps from database", counter, Context.Hashes.Count); dbCore.DbOps.GetAllApps(out List apps); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds get all apps from DB", stopwatch.Elapsed.TotalSeconds); - #endif + #endif - if(apps != null && apps.Count > 0) + if(apps != null && + apps.Count > 0) { DbEntry[] appsArray = new DbEntry[apps.Count]; apps.CopyTo(appsArray); long appCounter = 0; - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif foreach(DbEntry app in appsArray) { UpdateProgress?.Invoke(null, $"Check application id {app.Id}", appCounter, appsArray.Length); counter = 0; + foreach(KeyValuePair kvp in knownFiles) { UpdateProgress2?.Invoke(null, $"Checking for file {kvp.Value.Path}", counter, @@ -162,7 +175,8 @@ namespace apprepodbmgr.Core if(!dbCore.DbOps.ExistsFileInApp(kvp.Value.Sha256, app.Id)) { - if(apps.Contains(app)) apps.Remove(app); + if(apps.Contains(app)) + apps.Remove(app); // If one file is missing, the rest don't matter break; @@ -171,13 +185,15 @@ namespace apprepodbmgr.Core counter++; } - if(apps.Count == 0) break; // No apps left + if(apps.Count == 0) + break; // No apps left } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CheckDbForFiles(): Took {0} seconds correlate all files with all known applications", stopwatch.Elapsed.TotalSeconds); - #endif + #endif } if(AddApp != null) @@ -186,15 +202,16 @@ namespace apprepodbmgr.Core Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -203,16 +220,16 @@ namespace apprepodbmgr.Core try { long counter = 0; - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif foreach(KeyValuePair kvp in Context.Hashes) { UpdateProgress?.Invoke(null, "Adding files to database", counter, Context.Hashes.Count); if(!dbCore.DbOps.ExistsFile(kvp.Value.Sha256)) { - DbFile file = new DbFile + var file = new DbFile { Sha256 = kvp.Value.Sha256, ClamTime = null, @@ -222,6 +239,7 @@ namespace apprepodbmgr.Core HasVirus = null, VirusTotalTime = null }; + dbCore.DbOps.AddFile(file); AddFile?.Invoke(file); @@ -229,21 +247,23 @@ namespace apprepodbmgr.Core counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all files to the database", stopwatch.Elapsed.TotalSeconds); - #endif + #endif UpdateProgress?.Invoke(null, "Adding application information", counter, Context.Hashes.Count); dbCore.DbOps.AddApp(Context.DbInfo, out Context.DbInfo.Id); UpdateProgress?.Invoke(null, "Creating application table", counter, Context.Hashes.Count); dbCore.DbOps.CreateTableForApp(Context.DbInfo.Id); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif counter = 0; + foreach(KeyValuePair kvp in Context.Hashes) { UpdateProgress?.Invoke(null, "Adding files to application in database", counter, @@ -253,13 +273,16 @@ namespace apprepodbmgr.Core counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all files to the application in the database", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif counter = 0; + foreach(KeyValuePair kvp in Context.FoldersDict) { UpdateProgress?.Invoke(null, "Adding folders to application in database", counter, @@ -269,14 +292,18 @@ namespace apprepodbmgr.Core counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all folders to the database", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif counter = 0; - if(Context.SymlinksDict.Count > 0) dbCore.DbOps.CreateSymlinkTableForOs(Context.DbInfo.Id); + + if(Context.SymlinksDict.Count > 0) + dbCore.DbOps.CreateSymlinkTableForOs(Context.DbInfo.Id); foreach(KeyValuePair kvp in Context.SymlinksDict) { @@ -287,23 +314,25 @@ namespace apprepodbmgr.Core counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddFilesToDb(): Took {0} seconds to add all symbolic links to the database", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -317,16 +346,19 @@ namespace apprepodbmgr.Core if(string.IsNullOrEmpty(Settings.Current.DatabasePath)) { Failed?.Invoke("No database file specified"); + return; } dbCore = new SQLite(); + if(File.Exists(Settings.Current.DatabasePath)) { if(!dbCore.OpenDb(Settings.Current.DatabasePath, null, null, null)) { Failed?.Invoke("Could not open database, correct file selected?"); dbCore = null; + return; } } @@ -336,6 +368,7 @@ namespace apprepodbmgr.Core { Failed?.Invoke("Could not create database, correct file selected?"); dbCore = null; + return; } @@ -343,32 +376,33 @@ namespace apprepodbmgr.Core { Failed?.Invoke("Could not open database, correct file selected?"); dbCore = null; + return; } } Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } - public static void CloseDB() - { - dbCore?.CloseDb(); - } + public static void CloseDB() => dbCore?.CloseDb(); public static void RemoveApp(long id, string mdid) { - if(id == 0 || string.IsNullOrWhiteSpace(mdid)) return; + if(id == 0 || + string.IsNullOrWhiteSpace(mdid)) + return; dbCore.DbOps.RemoveApp(id); } @@ -381,12 +415,13 @@ namespace apprepodbmgr.Core const ulong PAGE = 2500; ulong offset = 0; - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif while(dbCore.DbOps.GetFiles(out List files, offset, PAGE)) { - if(files.Count == 0) break; + if(files.Count == 0) + break; UpdateProgress?.Invoke(null, $"Loaded file {offset} of {count}", (long)offset, (long)count); @@ -394,23 +429,25 @@ namespace apprepodbmgr.Core offset += PAGE; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.GetFilesFromDb(): Took {0} seconds to get all files from the database", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -422,21 +459,19 @@ namespace apprepodbmgr.Core Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } - public static DbFile GetDBFile(string hash) - { - return dbCore.DbOps.GetFile(hash); - } + public static DbFile GetDBFile(string hash) => dbCore.DbOps.GetFile(hash); } } \ No newline at end of file diff --git a/apprepodbmgr.Core/Workers/DiscImageChef.cs b/apprepodbmgr.Core/Workers/DiscImageChef.cs index 1e1c080..40e522d 100644 --- a/apprepodbmgr.Core/Workers/DiscImageChef.cs +++ b/apprepodbmgr.Core/Workers/DiscImageChef.cs @@ -54,29 +54,33 @@ namespace apprepodbmgr.Core if(string.IsNullOrWhiteSpace(Context.SelectedFile)) { Failed?.Invoke("There is no file set"); + return; } string filesPath; - if(!string.IsNullOrEmpty(Context.TmpFolder) && Directory.Exists(Context.TmpFolder)) - filesPath = Context.TmpFolder; - else filesPath = Context.Path; + if(!string.IsNullOrEmpty(Context.TmpFolder) && + Directory.Exists(Context.TmpFolder)) + filesPath = Context.TmpFolder; + else + filesPath = Context.Path; string selectedFile = Path.Combine(filesPath, Context.SelectedFile); if(!File.Exists(selectedFile)) { Failed?.Invoke("Selected file does not exist"); + return; } - CICMMetadataType sidecar = new CICMMetadataType(); - PluginBase plugins = new PluginBase(); + var sidecar = new CICMMetadataType(); + var plugins = new PluginBase(); long maxProgress = 4; - FiltersList filtersList = new FiltersList(); + var filtersList = new FiltersList(); UpdateProgress?.Invoke(null, "Detecting image filter", 1, maxProgress); @@ -85,25 +89,28 @@ namespace apprepodbmgr.Core if(inputFilter == null) { Failed?.Invoke("Cannot open specified file."); + return; } try { - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif UpdateProgress?.Invoke(null, "Detecting image format", 2, maxProgress); IMediaImage imageFormat = ImageFormat.Detect(inputFilter); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddMedia(): Took {0} seconds to detect image format", stopwatch.Elapsed.TotalSeconds); - #endif + #endif if(imageFormat == null) { Failed?.Invoke("Image format not identified, not proceeding with analysis."); + return; } @@ -112,30 +119,32 @@ namespace apprepodbmgr.Core if(!imageFormat.Open(inputFilter)) { Failed?.Invoke("Unable to open image format\n" + "No error given"); + return; } } catch(Exception ex) { Failed?.Invoke("Unable to open image format\n" + $"Error: {ex.Message}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif return; } - FileInfo fi = new FileInfo(selectedFile); - FileStream fs = new FileStream(selectedFile, FileMode.Open, FileAccess.Read); + var fi = new FileInfo(selectedFile); + var fs = new FileStream(selectedFile, FileMode.Open, FileAccess.Read); - Checksum imgChkWorker = new Checksum(); + var imgChkWorker = new Checksum(); UpdateProgress?.Invoke(null, "Hashing image file", 3, maxProgress); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif byte[] data; long position = 0; + while(position < fi.Length - 524288) { data = new byte[524288]; @@ -148,7 +157,7 @@ namespace apprepodbmgr.Core position += 524288; } - data = new byte[fi.Length - position]; + data = new byte[fi.Length - position]; fs.Read(data, 0, (int)(fi.Length - position)); UpdateProgress2?.Invoke(null, $"{position} of {fi.Length} bytes", position, fi.Length); @@ -156,17 +165,19 @@ namespace apprepodbmgr.Core imgChkWorker.Update(data); fs.Close(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddMedia(): Took {0} seconds to hash image file", stopwatch.Elapsed.TotalSeconds); - #endif + #endif List imgChecksums = imgChkWorker.End(); UpdateProgress2?.Invoke(null, null, 0, 0); long currentProgress = 0; + switch(imageFormat.Info.XmlMediaType) { case XmlMediaType.OpticalDisc: @@ -175,21 +186,27 @@ namespace apprepodbmgr.Core UpdateProgress?.Invoke(null, "Hashing image file", 3, maxProgress); - sidecar.OpticalDisc = new OpticalDiscType[1]; + sidecar.OpticalDisc = new OpticalDiscType[1]; + sidecar.OpticalDisc[0] = new OpticalDiscType { Checksums = imgChecksums.ToArray(), - Image = new ImageType + Image = new ImageType { format = imageFormat.Format, offset = 0, offsetSpecified = true, Value = Path.GetFileName(selectedFile) }, - Size = fi.Length, - Sequence = new SequenceType {MediaTitle = imageFormat.Info.MediaTitle} + Size = fi.Length, + Sequence = new SequenceType + { + MediaTitle = imageFormat.Info.MediaTitle + } }; - if(imageFormat.Info.MediaSequence != 0 && imageFormat.Info.LastMediaSequence != 0) + + if(imageFormat.Info.MediaSequence != 0 && + imageFormat.Info.LastMediaSequence != 0) { sidecar.OpticalDisc[0].Sequence.MediaSequence = imageFormat.Info.MediaSequence; sidecar.OpticalDisc[0].Sequence.TotalMedia = imageFormat.Info.LastMediaSequence; @@ -204,168 +221,223 @@ namespace apprepodbmgr.Core currentProgress = 3; - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif foreach(MediaTagType tagType in imageFormat.Info.ReadableMediaTags) { currentProgress++; + UpdateProgress?.Invoke(null, $"Hashing file containing {tagType}", currentProgress, maxProgress); switch(tagType) { case MediaTagType.CD_ATIP: - sidecar.OpticalDisc[0].ATIP = new DumpType(); - sidecar.OpticalDisc[0].ATIP.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .CD_ATIP)) - .ToArray(); + sidecar.OpticalDisc[0].ATIP = new DumpType(); + + sidecar.OpticalDisc[0].ATIP.Checksums = Checksum. + GetChecksums(imageFormat. + ReadDiskTag(MediaTagType. + CD_ATIP)). + ToArray(); + sidecar.OpticalDisc[0].ATIP.Size = imageFormat.ReadDiskTag(MediaTagType.CD_ATIP).Length; + ATIP.CDATIP? atip = ATIP.Decode(imageFormat.ReadDiskTag(MediaTagType.CD_ATIP)); + if(atip.HasValue) if(atip.Value.DDCD) dskType = atip.Value.DiscType ? MediaType.DDCDRW : MediaType.DDCDR; else dskType = atip.Value.DiscType ? MediaType.CDRW : MediaType.CDR; + break; case MediaTagType.DVD_BCA: - sidecar.OpticalDisc[0].BCA = new DumpType(); - sidecar.OpticalDisc[0].BCA.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .DVD_BCA)) - .ToArray(); + sidecar.OpticalDisc[0].BCA = new DumpType(); + + sidecar.OpticalDisc[0].BCA.Checksums = Checksum. + GetChecksums(imageFormat. + ReadDiskTag(MediaTagType. + DVD_BCA)). + ToArray(); + sidecar.OpticalDisc[0].BCA.Size = imageFormat.ReadDiskTag(MediaTagType.DVD_BCA).Length; + break; case MediaTagType.BD_BCA: - sidecar.OpticalDisc[0].BCA = new DumpType(); - sidecar.OpticalDisc[0].BCA.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .BD_BCA)) - .ToArray(); + sidecar.OpticalDisc[0].BCA = new DumpType(); + + sidecar.OpticalDisc[0].BCA.Checksums = Checksum. + GetChecksums(imageFormat. + ReadDiskTag(MediaTagType. + BD_BCA)).ToArray(); + sidecar.OpticalDisc[0].BCA.Size = imageFormat.ReadDiskTag(MediaTagType.BD_BCA).Length; + break; case MediaTagType.DVD_CMI: - sidecar.OpticalDisc[0].CMI = new DumpType(); + sidecar.OpticalDisc[0].CMI = new DumpType(); + CSS_CPRM.LeadInCopyright? cmi = CSS_CPRM.DecodeLeadInCopyright(imageFormat.ReadDiskTag(MediaTagType.DVD_CMI)); + if(cmi.HasValue) switch(cmi.Value.CopyrightType) { case CopyrightType.AACS: sidecar.OpticalDisc[0].CopyProtection = "AACS"; + break; case CopyrightType.CSS: sidecar.OpticalDisc[0].CopyProtection = "CSS"; + break; case CopyrightType.CPRM: sidecar.OpticalDisc[0].CopyProtection = "CPRM"; + break; } - sidecar.OpticalDisc[0].CMI.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .DVD_CMI)) - .ToArray(); + + sidecar.OpticalDisc[0].CMI.Checksums = Checksum. + GetChecksums(imageFormat. + ReadDiskTag(MediaTagType. + DVD_CMI)). + ToArray(); + sidecar.OpticalDisc[0].CMI.Size = imageFormat.ReadDiskTag(MediaTagType.DVD_CMI).Length; + break; case MediaTagType.DVD_DMI: - sidecar.OpticalDisc[0].DMI = new DumpType(); - sidecar.OpticalDisc[0].DMI.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .DVD_DMI)) - .ToArray(); + sidecar.OpticalDisc[0].DMI = new DumpType(); + + sidecar.OpticalDisc[0].DMI.Checksums = Checksum. + GetChecksums(imageFormat. + ReadDiskTag(MediaTagType. + DVD_DMI)). + ToArray(); + sidecar.OpticalDisc[0].DMI.Size = imageFormat.ReadDiskTag(MediaTagType.DVD_DMI).Length; + if(DMI.IsXbox(imageFormat.ReadDiskTag(MediaTagType.DVD_DMI))) { - dskType = MediaType.XGD; - sidecar.OpticalDisc[0].Dimensions = new DimensionsType {Diameter = 120}; + dskType = MediaType.XGD; + + sidecar.OpticalDisc[0].Dimensions = new DimensionsType + { + Diameter = 120 + }; } else if(DMI.IsXbox360(imageFormat.ReadDiskTag(MediaTagType.DVD_DMI))) { - dskType = MediaType.XGD2; - sidecar.OpticalDisc[0].Dimensions = new DimensionsType {Diameter = 120}; + dskType = MediaType.XGD2; + + sidecar.OpticalDisc[0].Dimensions = new DimensionsType + { + Diameter = 120 + }; } break; case MediaTagType.DVD_PFI: - sidecar.OpticalDisc[0].PFI = new DumpType(); - sidecar.OpticalDisc[0].PFI.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .DVD_PFI)) - .ToArray(); + sidecar.OpticalDisc[0].PFI = new DumpType(); + + sidecar.OpticalDisc[0].PFI.Checksums = Checksum. + GetChecksums(imageFormat. + ReadDiskTag(MediaTagType. + DVD_PFI)). + ToArray(); + sidecar.OpticalDisc[0].PFI.Size = imageFormat.ReadDiskTag(MediaTagType.DVD_PFI).Length; + PFI.PhysicalFormatInformation? pfi = PFI.Decode(imageFormat.ReadDiskTag(MediaTagType.DVD_PFI)); + if(pfi.HasValue) - if(dskType != MediaType.XGD && dskType != MediaType.XGD2 && + if(dskType != MediaType.XGD && + dskType != MediaType.XGD2 && dskType != MediaType.XGD3) { switch(pfi.Value.DiskCategory) { case DiskCategory.DVDPR: dskType = MediaType.DVDPR; + break; case DiskCategory.DVDPRDL: dskType = MediaType.DVDPRDL; + break; case DiskCategory.DVDPRW: dskType = MediaType.DVDPRW; + break; case DiskCategory.DVDPRWDL: dskType = MediaType.DVDPRWDL; + break; case DiskCategory.DVDR: dskType = MediaType.DVDR; + break; case DiskCategory.DVDRAM: dskType = MediaType.DVDRAM; + break; case DiskCategory.DVDROM: dskType = MediaType.DVDROM; + break; case DiskCategory.DVDRW: dskType = MediaType.DVDRW; + break; case DiskCategory.HDDVDR: dskType = MediaType.HDDVDR; + break; case DiskCategory.HDDVDRAM: dskType = MediaType.HDDVDRAM; + break; case DiskCategory.HDDVDROM: dskType = MediaType.HDDVDROM; + break; case DiskCategory.HDDVDRW: dskType = MediaType.HDDVDRW; + break; case DiskCategory.Nintendo: dskType = MediaType.GOD; + break; case DiskCategory.UMD: dskType = MediaType.UMD; + break; } - if(dskType == MediaType.DVDR && pfi.Value.PartVersion == 6) + if(dskType == MediaType.DVDR && + pfi.Value.PartVersion == 6) dskType = MediaType.DVDRDL; - if(dskType == MediaType.DVDRW && pfi.Value.PartVersion == 3) + + if(dskType == MediaType.DVDRW && + pfi.Value.PartVersion == 3) dskType = MediaType.DVDRWDL; - if(dskType == MediaType.GOD && pfi.Value.DiscSize == DVDSize.OneTwenty) + + if(dskType == MediaType.GOD && + pfi.Value.DiscSize == DVDSize.OneTwenty) dskType = MediaType.WOD; sidecar.OpticalDisc[0].Dimensions = new DimensionsType(); + if(dskType == MediaType.UMD) sidecar.OpticalDisc[0].Dimensions.Diameter = 60; else if(pfi.Value.DiscSize == DVDSize.Eighty) @@ -376,32 +448,39 @@ namespace apprepodbmgr.Core break; case MediaTagType.CD_PMA: - sidecar.OpticalDisc[0].PMA = new DumpType(); - sidecar.OpticalDisc[0].PMA.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .CD_PMA)) - .ToArray(); + sidecar.OpticalDisc[0].PMA = new DumpType(); + + sidecar.OpticalDisc[0].PMA.Checksums = Checksum. + GetChecksums(imageFormat. + ReadDiskTag(MediaTagType. + CD_PMA)).ToArray(); + sidecar.OpticalDisc[0].PMA.Size = imageFormat.ReadDiskTag(MediaTagType.CD_PMA).Length; + break; } } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddMedia(): Took {0} seconds to hash media tags", stopwatch.Elapsed.TotalSeconds); - #endif + #endif try { - List sessions = imageFormat.Sessions; + List sessions = imageFormat.Sessions; sidecar.OpticalDisc[0].Sessions = sessions?.Count ?? 1; } - catch { sidecar.OpticalDisc[0].Sessions = 1; } + catch + { + sidecar.OpticalDisc[0].Sessions = 1; + } List tracks = imageFormat.Tracks; List trksLst = null; + if(tracks != null) { sidecar.OpticalDisc[0].Tracks = new int[1]; @@ -413,41 +492,52 @@ namespace apprepodbmgr.Core { currentProgress++; - TrackType xmlTrk = new TrackType(); + var xmlTrk = new TrackType(); + switch(trk.TrackType) { case DiscImageChef.DiscImages.TrackType.Audio: xmlTrk.TrackType1 = TrackTypeTrackType.audio; + break; case DiscImageChef.DiscImages.TrackType.CdMode2Form2: xmlTrk.TrackType1 = TrackTypeTrackType.m2f2; + break; case DiscImageChef.DiscImages.TrackType.CdMode2Formless: xmlTrk.TrackType1 = TrackTypeTrackType.mode2; + break; case DiscImageChef.DiscImages.TrackType.CdMode2Form1: xmlTrk.TrackType1 = TrackTypeTrackType.m2f1; + break; case DiscImageChef.DiscImages.TrackType.CdMode1: xmlTrk.TrackType1 = TrackTypeTrackType.mode1; + break; case DiscImageChef.DiscImages.TrackType.Data: switch(sidecar.OpticalDisc[0].DiscType) { case "BD": xmlTrk.TrackType1 = TrackTypeTrackType.bluray; + break; case "DDCD": xmlTrk.TrackType1 = TrackTypeTrackType.ddcd; + break; case "DVD": xmlTrk.TrackType1 = TrackTypeTrackType.dvd; + break; case "HD DVD": xmlTrk.TrackType1 = TrackTypeTrackType.hddvd; + break; default: xmlTrk.TrackType1 = TrackTypeTrackType.mode1; + break; } @@ -459,10 +549,12 @@ namespace apprepodbmgr.Core Session = trk.TrackSession, TrackNumber = (int)trk.TrackSequence }; + xmlTrk.StartSector = (long)trk.TrackStartSector; xmlTrk.EndSector = (long)trk.TrackEndSector; - if(trk.Indexes != null && trk.Indexes.ContainsKey(0)) + if(trk.Indexes != null && + trk.Indexes.ContainsKey(0)) if(trk.Indexes.TryGetValue(0, out ulong idx0)) xmlTrk.StartSector = (long)idx0; @@ -472,14 +564,20 @@ namespace apprepodbmgr.Core case "GD": xmlTrk.StartMSF = LbaToMsf(xmlTrk.StartSector); xmlTrk.EndMSF = LbaToMsf(xmlTrk.EndSector); + break; case "DDCD": xmlTrk.StartMSF = DdcdLbaToMsf(xmlTrk.StartSector); xmlTrk.EndMSF = DdcdLbaToMsf(xmlTrk.EndSector); + break; } - xmlTrk.Image = new ImageType {Value = Path.GetFileName(trk.TrackFile)}; + xmlTrk.Image = new ImageType + { + Value = Path.GetFileName(trk.TrackFile) + }; + if(trk.TrackFileOffset > 0) { xmlTrk.Image.offset = (long)trk.TrackFileOffset; @@ -487,12 +585,11 @@ namespace apprepodbmgr.Core } xmlTrk.Image.format = trk.TrackFileType; - xmlTrk.Size = - (xmlTrk.EndSector - xmlTrk.StartSector + 1) * trk.TrackRawBytesPerSector; + xmlTrk.Size = ((xmlTrk.EndSector - xmlTrk.StartSector) + 1) * trk.TrackRawBytesPerSector; xmlTrk.BytesPerSector = trk.TrackBytesPerSector; const uint SECTORS_TO_READ = 512; - ulong sectors = (ulong)(xmlTrk.EndSector - xmlTrk.StartSector + 1); + ulong sectors = (ulong)((xmlTrk.EndSector - xmlTrk.StartSector) + 1); ulong doneSectors = 0; // If there is only one track, and it's the same as the image file (e.g. ".iso" files), don't re-checksum. @@ -503,11 +600,11 @@ namespace apprepodbmgr.Core UpdateProgress?.Invoke(null, $"Hashing track {trk.TrackSequence}", currentProgress, maxProgress); - Checksum trkChkWorker = new Checksum(); + var trkChkWorker = new Checksum(); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif while(doneSectors < sectors) { byte[] sector; @@ -516,16 +613,20 @@ namespace apprepodbmgr.Core { sector = imageFormat.ReadSectorsLong(doneSectors, SECTORS_TO_READ, (uint)xmlTrk.Sequence.TrackNumber); + UpdateProgress2?.Invoke(null, $"Sector {doneSectors} of {sectors}", (long)doneSectors, (long)sectors); + doneSectors += SECTORS_TO_READ; } else { sector = imageFormat.ReadSectorsLong(doneSectors, (uint)(sectors - doneSectors), (uint)xmlTrk.Sequence.TrackNumber); + UpdateProgress2?.Invoke(null, $"Sector {doneSectors} of {sectors}", (long)doneSectors, (long)sectors); + doneSectors += sectors - doneSectors; } @@ -533,11 +634,12 @@ namespace apprepodbmgr.Core } List trkChecksums = trkChkWorker.End(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddMedia(): Took {0} seconds to hash track {1}", stopwatch.Elapsed.TotalSeconds, trk.TrackSequence); - #endif + #endif xmlTrk.Checksums = trkChecksums.ToArray(); } @@ -549,20 +651,27 @@ namespace apprepodbmgr.Core UpdateProgress?.Invoke(null, $"Hashing subchannel of track {trk.TrackSequence}", currentProgress, maxProgress); - xmlTrk.SubChannel = new SubChannelType {Image = new ImageType()}; + xmlTrk.SubChannel = new SubChannelType + { + Image = new ImageType() + }; + switch(trk.TrackSubchannelType) { case TrackSubchannelType.Packed: case TrackSubchannelType.PackedInterleaved: xmlTrk.SubChannel.Image.format = "rw"; + break; case TrackSubchannelType.Raw: case TrackSubchannelType.RawInterleaved: xmlTrk.SubChannel.Image.format = "rw_raw"; + break; case TrackSubchannelType.Q16: case TrackSubchannelType.Q16Interleaved: xmlTrk.SubChannel.Image.format = "q16"; + break; } @@ -575,16 +684,16 @@ namespace apprepodbmgr.Core xmlTrk.SubChannel.Image.Value = trk.TrackSubchannelFile; // TODO: Packed subchannel has different size? - xmlTrk.SubChannel.Size = (xmlTrk.EndSector - xmlTrk.StartSector + 1) * 96; + xmlTrk.SubChannel.Size = ((xmlTrk.EndSector - xmlTrk.StartSector) + 1) * 96; - Checksum subChkWorker = new Checksum(); + var subChkWorker = new Checksum(); - sectors = (ulong)(xmlTrk.EndSector - xmlTrk.StartSector + 1); + sectors = (ulong)((xmlTrk.EndSector - xmlTrk.StartSector) + 1); doneSectors = 0; - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif while(doneSectors < sectors) { byte[] sector; @@ -594,8 +703,10 @@ namespace apprepodbmgr.Core sector = imageFormat.ReadSectorsTag(doneSectors, SECTORS_TO_READ, (uint)xmlTrk.Sequence.TrackNumber, SectorTagType.CdSectorSubchannel); + UpdateProgress2?.Invoke(null, $"Sector {doneSectors} of {sectors}", position, fi.Length); + doneSectors += SECTORS_TO_READ; } else @@ -603,8 +714,10 @@ namespace apprepodbmgr.Core sector = imageFormat.ReadSectorsTag(doneSectors, (uint)(sectors - doneSectors), (uint)xmlTrk.Sequence.TrackNumber, SectorTagType.CdSectorSubchannel); + UpdateProgress2?.Invoke(null, $"Sector {doneSectors} of {sectors}", position, fi.Length); + doneSectors += sectors - doneSectors; } @@ -614,20 +727,21 @@ namespace apprepodbmgr.Core List subChecksums = subChkWorker.End(); xmlTrk.SubChannel.Checksums = subChecksums.ToArray(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddMedia(): Took {0} seconds to hash subchannel of track {1}", stopwatch.Elapsed.TotalSeconds, trk.TrackSequence); - #endif + #endif UpdateProgress2?.Invoke(null, null, 0, 0); } UpdateProgress?.Invoke(null, "Checking filesystems", maxProgress - 1, maxProgress); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif List partitions = new List(); foreach(IPartition partplugin in plugins.PartPluginsList.Values) @@ -636,9 +750,11 @@ namespace apprepodbmgr.Core partitions.AddRange(_partitions); xmlTrk.FileSystemInformation = new PartitionType[1]; + if(partitions.Count > 0) { xmlTrk.FileSystemInformation = new PartitionType[partitions.Count]; + for(int i = 0; i < partitions.Count; i++) { xmlTrk.FileSystemInformation[i] = new PartitionType @@ -656,7 +772,8 @@ namespace apprepodbmgr.Core foreach(IFilesystem plugin in plugins.PluginsList.Values) try { - if(!plugin.Identify(imageFormat, partitions[i])) continue; + if(!plugin.Identify(imageFormat, partitions[i])) + continue; plugin.GetInformation(imageFormat, partitions[i], out _, null); lstFs.Add(plugin.XmlFsType); @@ -665,15 +782,19 @@ namespace apprepodbmgr.Core { case "Opera": dskType = MediaType.ThreeDO; + break; case "PC Engine filesystem": dskType = MediaType.SuperCDROM2; + break; case "Nintendo Wii filesystem": dskType = MediaType.WOD; + break; case "Nintendo Gamecube filesystem": dskType = MediaType.GOD; + break; } } @@ -684,7 +805,8 @@ namespace apprepodbmgr.Core //DicConsole.DebugWriteLine("Create-sidecar command", "Plugin {0} crashed", _plugin.Name); } - if(lstFs.Count > 0) xmlTrk.FileSystemInformation[i].FileSystems = lstFs.ToArray(); + if(lstFs.Count > 0) + xmlTrk.FileSystemInformation[i].FileSystems = lstFs.ToArray(); } } else @@ -695,10 +817,10 @@ namespace apprepodbmgr.Core StartSector = (int)xmlTrk.StartSector }; - Partition xmlPart = new Partition + var xmlPart = new Partition { Start = (ulong)xmlTrk.StartSector, - Length = (ulong)(xmlTrk.EndSector - xmlTrk.StartSector + 1) + Length = (ulong)((xmlTrk.EndSector - xmlTrk.StartSector) + 1) }; List lstFs = new List(); @@ -706,7 +828,8 @@ namespace apprepodbmgr.Core foreach(IFilesystem _plugin in plugins.PluginsList.Values) try { - if(!_plugin.Identify(imageFormat, xmlPart)) continue; + if(!_plugin.Identify(imageFormat, xmlPart)) + continue; _plugin.GetInformation(imageFormat, xmlPart, out _, null); lstFs.Add(_plugin.XmlFsType); @@ -715,15 +838,19 @@ namespace apprepodbmgr.Core { case "Opera": dskType = MediaType.ThreeDO; + break; case "PC Engine filesystem": dskType = MediaType.SuperCDROM2; + break; case "Nintendo Wii filesystem": dskType = MediaType.WOD; + break; case "Nintendo Gamecube filesystem": dskType = MediaType.GOD; + break; } } @@ -734,23 +861,27 @@ namespace apprepodbmgr.Core //DicConsole.DebugWriteLine("Create-sidecar command", "Plugin {0} crashed", _plugin.Name); } - if(lstFs.Count > 0) xmlTrk.FileSystemInformation[0].FileSystems = lstFs.ToArray(); + if(lstFs.Count > 0) + xmlTrk.FileSystemInformation[0].FileSystems = lstFs.ToArray(); } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddMedia(): Took {0} seconds to check all filesystems on track {1}", stopwatch.Elapsed.TotalSeconds, trk.TrackSequence); - #endif + #endif trksLst.Add(xmlTrk); } UpdateProgress?.Invoke(null, "Finishing", maxProgress, maxProgress); - if(trksLst != null) sidecar.OpticalDisc[0].Track = trksLst.ToArray(); + if(trksLst != null) + sidecar.OpticalDisc[0].Track = trksLst.ToArray(); DiscImageChef.Metadata.MediaType.MediaTypeToString(dskType, out string dscType, out string dscSubType); + sidecar.OpticalDisc[0].DiscType = dscType; sidecar.OpticalDisc[0].DiscSubType = dscSubType; @@ -763,12 +894,17 @@ namespace apprepodbmgr.Core sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents = new ExtentType[0]; sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].Start = 0; sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].End = imageFormat.Info.Sectors; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Manufacturer = + + sidecar.OpticalDisc[0].DumpHardwareArray[0].Manufacturer = imageFormat.Info.DriveManufacturer; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Model = imageFormat.Info.DriveModel; + + sidecar.OpticalDisc[0].DumpHardwareArray[0].Model = imageFormat.Info.DriveModel; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Firmware = imageFormat.Info.DriveFirmwareRevision; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Serial = imageFormat.Info.DriveSerialNumber; + + sidecar.OpticalDisc[0].DumpHardwareArray[0].Serial = imageFormat.Info.DriveSerialNumber; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software = new SoftwareType { Name = imageFormat.Info.Application, @@ -778,6 +914,7 @@ namespace apprepodbmgr.Core Context.WorkingDisc = sidecar.OpticalDisc[0]; Finished?.Invoke(); + return; } case XmlMediaType.BlockMedia: @@ -785,21 +922,27 @@ namespace apprepodbmgr.Core maxProgress = 3 + imageFormat.Info.ReadableMediaTags.Count; UpdateProgress?.Invoke(null, "Hashing image file", 3, maxProgress); - sidecar.BlockMedia = new BlockMediaType[1]; + sidecar.BlockMedia = new BlockMediaType[1]; + sidecar.BlockMedia[0] = new BlockMediaType { Checksums = imgChecksums.ToArray(), - Image = new ImageType + Image = new ImageType { format = imageFormat.Format, offset = 0, offsetSpecified = true, Value = Path.GetFileName(selectedFile) }, - Size = fi.Length, - Sequence = new SequenceType {MediaTitle = imageFormat.Info.MediaTitle} + Size = fi.Length, + Sequence = new SequenceType + { + MediaTitle = imageFormat.Info.MediaTitle + } }; - if(imageFormat.Info.MediaSequence != 0 && imageFormat.Info.LastMediaSequence != 0) + + if(imageFormat.Info.MediaSequence != 0 && + imageFormat.Info.LastMediaSequence != 0) { sidecar.BlockMedia[0].Sequence.MediaSequence = imageFormat.Info.MediaSequence; sidecar.BlockMedia[0].Sequence.TotalMedia = imageFormat.Info.LastMediaSequence; @@ -812,47 +955,48 @@ namespace apprepodbmgr.Core currentProgress = 3; - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif foreach(MediaTagType tagType in imageFormat.Info.ReadableMediaTags) { currentProgress++; + UpdateProgress?.Invoke(null, $"Hashing file containing {tagType}", currentProgress, maxProgress); switch(tagType) { case MediaTagType.ATAPI_IDENTIFY: - sidecar.BlockMedia[0].ATA = new ATAType(); - sidecar.BlockMedia[0].ATA.Identify = new DumpType(); - sidecar.BlockMedia[0].ATA.Identify.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .ATAPI_IDENTIFY)) - .ToArray(); + sidecar.BlockMedia[0].ATA = new ATAType(); + sidecar.BlockMedia[0].ATA.Identify = new DumpType(); + + sidecar.BlockMedia[0].ATA.Identify.Checksums = Checksum. + GetChecksums(imageFormat.ReadDiskTag(MediaTagType.ATAPI_IDENTIFY)).ToArray(); + sidecar.BlockMedia[0].ATA.Identify.Size = imageFormat.ReadDiskTag(MediaTagType.ATAPI_IDENTIFY).Length; + break; case MediaTagType.ATA_IDENTIFY: - sidecar.BlockMedia[0].ATA = new ATAType(); - sidecar.BlockMedia[0].ATA.Identify = new DumpType(); - sidecar.BlockMedia[0].ATA.Identify.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .ATA_IDENTIFY)) - .ToArray(); + sidecar.BlockMedia[0].ATA = new ATAType(); + sidecar.BlockMedia[0].ATA.Identify = new DumpType(); + + sidecar.BlockMedia[0].ATA.Identify.Checksums = Checksum. + GetChecksums(imageFormat.ReadDiskTag(MediaTagType.ATA_IDENTIFY)).ToArray(); + sidecar.BlockMedia[0].ATA.Identify.Size = imageFormat.ReadDiskTag(MediaTagType.ATA_IDENTIFY).Length; + break; case MediaTagType.PCMCIA_CIS: - byte[] cis = - imageFormat.ReadDiskTag(MediaTagType.PCMCIA_CIS); + byte[] cis = imageFormat.ReadDiskTag(MediaTagType.PCMCIA_CIS); sidecar.BlockMedia[0].PCMCIA = new PCMCIAType(); sidecar.BlockMedia[0].PCMCIA.CIS = new DumpType(); sidecar.BlockMedia[0].PCMCIA.CIS.Checksums = Checksum.GetChecksums(cis).ToArray(); sidecar.BlockMedia[0].PCMCIA.CIS.Size = cis.Length; - Tuple[] tuples = CIS.GetTuples(cis); + Tuple[] tuples = CIS.GetTuples(cis); + if(tuples != null) foreach(Tuple tuple in tuples) if(tuple.Code == TupleCodes.CISTPL_MANFID) @@ -864,10 +1008,10 @@ namespace apprepodbmgr.Core { sidecar.BlockMedia[0].PCMCIA.ManufacturerCode = manfid.ManufacturerID; - sidecar.BlockMedia[0].PCMCIA.CardCode = - manfid.CardID; + + sidecar.BlockMedia[0].PCMCIA.CardCode = manfid.CardID; sidecar.BlockMedia[0].PCMCIA.ManufacturerCodeSpecified = true; - sidecar.BlockMedia[0].PCMCIA.CardCodeSpecified = true; + sidecar.BlockMedia[0].PCMCIA.CardCodeSpecified = true; } } else if(tuple.Code == TupleCodes.CISTPL_VERS_1) @@ -878,8 +1022,10 @@ namespace apprepodbmgr.Core { sidecar.BlockMedia[0].PCMCIA.Manufacturer = vers.Manufacturer; sidecar.BlockMedia[0].PCMCIA.ProductName = vers.Product; - sidecar.BlockMedia[0].PCMCIA.Compliance = + + sidecar.BlockMedia[0].PCMCIA.Compliance = $"{vers.MajorVersion}.{vers.MinorVersion}"; + sidecar.BlockMedia[0].PCMCIA.AdditionalInformation = vers.AdditionalInformation; } @@ -887,60 +1033,63 @@ namespace apprepodbmgr.Core break; case MediaTagType.SCSI_INQUIRY: - sidecar.BlockMedia[0].SCSI = new SCSIType(); - sidecar.BlockMedia[0].SCSI.Inquiry = new DumpType(); - sidecar.BlockMedia[0].SCSI.Inquiry.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .SCSI_INQUIRY)) - .ToArray(); + sidecar.BlockMedia[0].SCSI = new SCSIType(); + sidecar.BlockMedia[0].SCSI.Inquiry = new DumpType(); + + sidecar.BlockMedia[0].SCSI.Inquiry.Checksums = Checksum. + GetChecksums(imageFormat.ReadDiskTag(MediaTagType.SCSI_INQUIRY)).ToArray(); + sidecar.BlockMedia[0].SCSI.Inquiry.Size = imageFormat.ReadDiskTag(MediaTagType.SCSI_INQUIRY).Length; + break; case MediaTagType.SD_CID: if(sidecar.BlockMedia[0].SecureDigital == null) - sidecar.BlockMedia[0].SecureDigital = new SecureDigitalType(); - sidecar.BlockMedia[0].SecureDigital.CID = new DumpType(); - sidecar.BlockMedia[0].SecureDigital.CID.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .SD_CID)) - .ToArray(); + sidecar.BlockMedia[0].SecureDigital = new SecureDigitalType(); + + sidecar.BlockMedia[0].SecureDigital.CID = new DumpType(); + + sidecar.BlockMedia[0].SecureDigital.CID.Checksums = Checksum. + GetChecksums(imageFormat.ReadDiskTag(MediaTagType.SD_CID)).ToArray(); + sidecar.BlockMedia[0].SecureDigital.CID.Size = imageFormat.ReadDiskTag(MediaTagType.SD_CID).Length; + break; case MediaTagType.SD_CSD: if(sidecar.BlockMedia[0].SecureDigital == null) - sidecar.BlockMedia[0].SecureDigital = new SecureDigitalType(); - sidecar.BlockMedia[0].SecureDigital.CSD = new DumpType(); - sidecar.BlockMedia[0].SecureDigital.CSD.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .SD_CSD)) - .ToArray(); + sidecar.BlockMedia[0].SecureDigital = new SecureDigitalType(); + + sidecar.BlockMedia[0].SecureDigital.CSD = new DumpType(); + + sidecar.BlockMedia[0].SecureDigital.CSD.Checksums = Checksum. + GetChecksums(imageFormat.ReadDiskTag(MediaTagType.SD_CSD)).ToArray(); + sidecar.BlockMedia[0].SecureDigital.CSD.Size = imageFormat.ReadDiskTag(MediaTagType.SD_CSD).Length; + break; case MediaTagType.MMC_ExtendedCSD: if(sidecar.BlockMedia[0].SecureDigital == null) - sidecar.BlockMedia[0].SecureDigital = - new SecureDigitalType(); - sidecar.BlockMedia[0].MultiMediaCard.ExtendedCSD = new DumpType(); - sidecar.BlockMedia[0].MultiMediaCard.ExtendedCSD.Checksums = Checksum - .GetChecksums(imageFormat - .ReadDiskTag(MediaTagType - .MMC_ExtendedCSD)) - .ToArray(); + sidecar.BlockMedia[0].SecureDigital = new SecureDigitalType(); + + sidecar.BlockMedia[0].MultiMediaCard.ExtendedCSD = new DumpType(); + + sidecar.BlockMedia[0].MultiMediaCard.ExtendedCSD.Checksums = Checksum. + GetChecksums(imageFormat.ReadDiskTag(MediaTagType.MMC_ExtendedCSD)).ToArray(); + sidecar.BlockMedia[0].MultiMediaCard.ExtendedCSD.Size = imageFormat.ReadDiskTag(MediaTagType.MMC_ExtendedCSD).Length; + break; } } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddMedia(): Took {0} seconds to hash media tags", stopwatch.Elapsed.TotalSeconds); - #endif + #endif // If there is only one track, and it's the same as the image file (e.g. ".iso" files), don't re-checksum. if(imageFormat.Id == new Guid("12345678-AAAA-BBBB-CCCC-123456789000")) @@ -953,11 +1102,11 @@ namespace apprepodbmgr.Core UpdateProgress?.Invoke(null, "Hashing media contents", currentProgress, maxProgress); - Checksum cntChkWorker = new Checksum(); + var cntChkWorker = new Checksum(); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif while(doneSectors < sectors) { byte[] sector; @@ -965,15 +1114,19 @@ namespace apprepodbmgr.Core if(sectors - doneSectors >= SECTORS_TO_READ) { sector = imageFormat.ReadSectors(doneSectors, SECTORS_TO_READ); + UpdateProgress2?.Invoke(null, $"Sector {doneSectors} of {sectors}", (long)doneSectors, (long)sectors); + doneSectors += SECTORS_TO_READ; } else { sector = imageFormat.ReadSectors(doneSectors, (uint)(sectors - doneSectors)); + UpdateProgress2?.Invoke(null, $"Sector {doneSectors} of {sectors}", (long)doneSectors, (long)sectors); + doneSectors += sectors - doneSectors; } @@ -981,17 +1134,19 @@ namespace apprepodbmgr.Core } List cntChecksums = cntChkWorker.End(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddMedia(): Took {0} seconds to hash media contents", stopwatch.Elapsed.TotalSeconds); - #endif + #endif sidecar.BlockMedia[0].ContentChecksums = cntChecksums.ToArray(); } DiscImageChef.Metadata.MediaType.MediaTypeToString(imageFormat.Info.MediaType, out string dskType, out string dskSubType); + sidecar.BlockMedia[0].DiskType = dskType; sidecar.BlockMedia[0].DiskSubType = dskSubType; @@ -1000,27 +1155,31 @@ namespace apprepodbmgr.Core sidecar.BlockMedia[0].LogicalBlocks = (long)imageFormat.Info.Sectors; sidecar.BlockMedia[0].LogicalBlockSize = (int)imageFormat.Info.SectorSize; + // TODO: Detect it sidecar.BlockMedia[0].PhysicalBlockSize = (int)imageFormat.Info.SectorSize; UpdateProgress?.Invoke(null, "Checking filesystems", maxProgress - 1, maxProgress); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif List partitions = new List(); foreach(IPartition partplugin in plugins.PartPluginsList.Values) { - if(!partplugin.GetInformation(imageFormat, out partitions, 0)) continue; + if(!partplugin.GetInformation(imageFormat, out partitions, 0)) + continue; break; } sidecar.BlockMedia[0].FileSystemInformation = new PartitionType[1]; + if(partitions.Count > 0) { sidecar.BlockMedia[0].FileSystemInformation = new PartitionType[partitions.Count]; + for(int i = 0; i < partitions.Count; i++) { sidecar.BlockMedia[0].FileSystemInformation[i] = new PartitionType @@ -1038,7 +1197,8 @@ namespace apprepodbmgr.Core foreach(IFilesystem plugin in plugins.PluginsList.Values) try { - if(!plugin.Identify(imageFormat, partitions[i])) continue; + if(!plugin.Identify(imageFormat, partitions[i])) + continue; plugin.GetInformation(imageFormat, partitions[i], out _, null); lstFs.Add(plugin.XmlFsType); @@ -1062,14 +1222,19 @@ namespace apprepodbmgr.Core EndSector = (int)(imageFormat.Info.Sectors - 1) }; - Partition wholePart = new Partition {Start = 0, Length = imageFormat.Info.Sectors}; + var wholePart = new Partition + { + Start = 0, + Length = imageFormat.Info.Sectors + }; List lstFs = new List(); foreach(IFilesystem _plugin in plugins.PluginsList.Values) try { - if(!_plugin.Identify(imageFormat, wholePart)) continue; + if(!_plugin.Identify(imageFormat, wholePart)) + continue; _plugin.GetInformation(imageFormat, wholePart, out _, null); lstFs.Add(_plugin.XmlFsType); @@ -1084,26 +1249,30 @@ namespace apprepodbmgr.Core if(lstFs.Count > 0) sidecar.BlockMedia[0].FileSystemInformation[0].FileSystems = lstFs.ToArray(); } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.AddMedia(): Took {0} seconds to check all filesystems", stopwatch.Elapsed.TotalSeconds); - #endif + #endif // TODO: Implement support for getting CHS UpdateProgress?.Invoke(null, "Finishing", maxProgress, maxProgress); Context.WorkingDisk = sidecar.BlockMedia[0]; Finished?.Invoke(); + return; } case XmlMediaType.LinearMedia: { Failed?.Invoke("Linear media not yet supported."); + return; } case XmlMediaType.AudioMedia: { Failed?.Invoke("Audio media not yet supported."); + return; } } @@ -1113,15 +1282,16 @@ namespace apprepodbmgr.Core catch(Exception ex) { Failed?.Invoke($"Error reading file: {ex.Message}\n{ex.StackTrace}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } static string LbaToMsf(long lba) { long m, s, f; + if(lba >= -150) { m = (lba + 150) / (75 * 60); @@ -1145,6 +1315,7 @@ namespace apprepodbmgr.Core static string DdcdLbaToMsf(long lba) { long h, m, s, f; + if(lba >= -150) { h = (lba + 150) / (75 * 60 * 60); @@ -1157,13 +1328,13 @@ namespace apprepodbmgr.Core } else { - h = (lba + 450150 * 2) / (75 * 60 * 60); - lba -= h * (75 * 60 * 60); - m = (lba + 450150 * 2) / (75 * 60); - lba -= m * (75 * 60); - s = (lba + 450150 * 2) / 75; - lba -= s * 75; - f = lba + 450150 * 2; + h = (lba + (450150 * 2)) / (75 * 60 * 60); + lba -= h * (75 * 60 * 60); + m = (lba + (450150 * 2)) / (75 * 60); + lba -= m * (75 * 60); + s = (lba + (450150 * 2)) / 75; + lba -= s * 75; + f = lba + (450150 * 2); } return string.Format("{3}:{0:D2}:{1:D2}:{2:D2}", m, s, f, h); diff --git a/apprepodbmgr.Core/Workers/Files.cs b/apprepodbmgr.Core/Workers/Files.cs index 2ada2f0..922ec6e 100644 --- a/apprepodbmgr.Core/Workers/Files.cs +++ b/apprepodbmgr.Core/Workers/Files.cs @@ -53,53 +53,63 @@ namespace apprepodbmgr.Core { string filesPath; - if(!string.IsNullOrEmpty(Context.TmpFolder) && Directory.Exists(Context.TmpFolder)) - filesPath = Context.TmpFolder; - else filesPath = Context.Path; + if(!string.IsNullOrEmpty(Context.TmpFolder) && + Directory.Exists(Context.TmpFolder)) + filesPath = Context.TmpFolder; + else + filesPath = Context.Path; - if(string.IsNullOrEmpty(filesPath)) Failed?.Invoke("Path is null or empty"); + if(string.IsNullOrEmpty(filesPath)) + Failed?.Invoke("Path is null or empty"); - if(!Directory.Exists(filesPath)) Failed?.Invoke("Directory not found"); + if(!Directory.Exists(filesPath)) + Failed?.Invoke("Directory not found"); try { - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif Context.Files = IO.EnumerateFiles(filesPath, "*", SearchOption.AllDirectories, false, false); Context.Files.Sort(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.FindFiles(): Took {0} seconds to find all files", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif Context.Folders = IO.EnumerateDirectories(filesPath, "*", SearchOption.AllDirectories, false, false); Context.Folders.Sort(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.FindFiles(): Took {0} seconds to find all folders", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif Context.Symlinks = IO.EnumerateSymlinks(filesPath, "*", SearchOption.AllDirectories); Context.Symlinks.Sort(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.FindFiles(): Took {0} seconds to find all symbolic links", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -152,64 +162,103 @@ namespace apprepodbmgr.Core DetectOS.GetRealPlatformID() == PlatformID.Win32S || DetectOS.GetRealPlatformID() == PlatformID.Win32NT || DetectOS.GetRealPlatformID() == PlatformID.Win32Windows || - DetectOS.GetRealPlatformID() == PlatformID.WindowsPhone) && Context.Symlinks.Count > 0) + DetectOS.GetRealPlatformID() == PlatformID.WindowsPhone) && + Context.Symlinks.Count > 0) { Failed?.Invoke("Source contain unsupported symbolic links, not continuing."); + return; } - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif long counter = 1; + foreach(string file in Context.Files) { // An already known metadata file, skip it if(alreadyMetadata.Contains(file)) { counter++; + continue; } switch(Path.GetExtension(file).ToLowerInvariant()) { case ".xml": - FileStream xrs = new FileStream(file, FileMode.Open, FileAccess.Read); - XmlReaderSettings xrt = new XmlReaderSettings {DtdProcessing = DtdProcessing.Ignore}; + var xrs = new FileStream(file, FileMode.Open, FileAccess.Read); + + var xrt = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Ignore + }; + + var xr = XmlReader.Create(xrs, xrt); + var xs = new XmlSerializer(typeof(CICMMetadataType)); - XmlReader xr = XmlReader.Create(xrs, xrt); - XmlSerializer xs = new XmlSerializer(typeof(CICMMetadataType)); try { if(xs.CanDeserialize(xr)) { - CICMMetadataType thisMetadata = (CICMMetadataType)xs.Deserialize(xr); + var thisMetadata = (CICMMetadataType)xs.Deserialize(xr); + if(thisMetadata.Architectures != null) architectures.AddRange(thisMetadata.Architectures); - if(thisMetadata.Barcodes != null) barcodes.AddRange(thisMetadata.Barcodes); - if(thisMetadata.BlockMedia != null) disks.AddRange(thisMetadata.BlockMedia); - if(thisMetadata.Categories != null) categories.AddRange(thisMetadata.Categories); - if(thisMetadata.Keywords != null) keywords.AddRange(thisMetadata.Keywords); - if(thisMetadata.Languages != null) languages.AddRange(thisMetadata.Languages); - if(thisMetadata.OpticalDisc != null) discs.AddRange(thisMetadata.OpticalDisc); + + if(thisMetadata.Barcodes != null) + barcodes.AddRange(thisMetadata.Barcodes); + + if(thisMetadata.BlockMedia != null) + disks.AddRange(thisMetadata.BlockMedia); + + if(thisMetadata.Categories != null) + categories.AddRange(thisMetadata.Categories); + + if(thisMetadata.Keywords != null) + keywords.AddRange(thisMetadata.Keywords); + + if(thisMetadata.Languages != null) + languages.AddRange(thisMetadata.Languages); + + if(thisMetadata.OpticalDisc != null) + discs.AddRange(thisMetadata.OpticalDisc); + if(thisMetadata.Subcategories != null) subcategories.AddRange(thisMetadata.Subcategories); - if(thisMetadata.Systems != null) systems.AddRange(thisMetadata.Systems); - if(thisMetadata.Author != null) authors.AddRange(thisMetadata.Author); - if(thisMetadata.Developer != null) developers.AddRange(thisMetadata.Developer); - if(thisMetadata.Performer != null) performers.AddRange(thisMetadata.Performer); - if(thisMetadata.Publisher != null) publishers.AddRange(thisMetadata.Publisher); + + if(thisMetadata.Systems != null) + systems.AddRange(thisMetadata.Systems); + + if(thisMetadata.Author != null) + authors.AddRange(thisMetadata.Author); + + if(thisMetadata.Developer != null) + developers.AddRange(thisMetadata.Developer); + + if(thisMetadata.Performer != null) + performers.AddRange(thisMetadata.Performer); + + if(thisMetadata.Publisher != null) + publishers.AddRange(thisMetadata.Publisher); + if(string.IsNullOrWhiteSpace(metadataName) && - !string.IsNullOrWhiteSpace(thisMetadata.Name)) metadataName = thisMetadata.Name; + !string.IsNullOrWhiteSpace(thisMetadata.Name)) + metadataName = thisMetadata.Name; + if(string.IsNullOrWhiteSpace(metadataPartNo) && !string.IsNullOrWhiteSpace(thisMetadata.PartNumber)) metadataPartNo = thisMetadata.PartNumber; + if(string.IsNullOrWhiteSpace(metadataSerial) && !string.IsNullOrWhiteSpace(thisMetadata.SerialNumber)) metadataSerial = thisMetadata.SerialNumber; + if(string.IsNullOrWhiteSpace(metadataVersion) && !string.IsNullOrWhiteSpace(thisMetadata.Version)) metadataVersion = thisMetadata.Version; + if(thisMetadata.ReleaseDateSpecified) if(thisMetadata.ReleaseDate > releaseDate) { @@ -223,23 +272,36 @@ namespace apprepodbmgr.Core releaseType = thisMetadata.ReleaseType; } - if(thisMetadata.Magazine != null) magazines.AddRange(thisMetadata.Magazine); - if(thisMetadata.Book != null) books.AddRange(thisMetadata.Book); + if(thisMetadata.Magazine != null) + magazines.AddRange(thisMetadata.Magazine); + + if(thisMetadata.Book != null) + books.AddRange(thisMetadata.Book); + if(thisMetadata.RequiredOperatingSystems != null) requiredOses.AddRange(thisMetadata.RequiredOperatingSystems); + if(thisMetadata.UserManual != null) usermanuals.AddRange(thisMetadata.UserManual); - if(thisMetadata.Advertisement != null) adverts.AddRange(thisMetadata.Advertisement); + + if(thisMetadata.Advertisement != null) + adverts.AddRange(thisMetadata.Advertisement); + if(thisMetadata.LinearMedia != null) linearmedias.AddRange(thisMetadata.LinearMedia); - if(thisMetadata.PCICard != null) pcis.AddRange(thisMetadata.PCICard); - if(thisMetadata.AudioMedia != null) audiomedias.AddRange(thisMetadata.AudioMedia); + + if(thisMetadata.PCICard != null) + pcis.AddRange(thisMetadata.PCICard); + + if(thisMetadata.AudioMedia != null) + audiomedias.AddRange(thisMetadata.AudioMedia); foundMetadata = true; string metadataFileWithoutExtension = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)); + alreadyMetadata.Add(metadataFileWithoutExtension + ".xml"); alreadyMetadata.Add(metadataFileWithoutExtension + ".xmL"); alreadyMetadata.Add(metadataFileWithoutExtension + ".xMl"); @@ -267,6 +329,7 @@ namespace apprepodbmgr.Core xr.Close(); xrs.Close(); + continue; } } @@ -278,40 +341,69 @@ namespace apprepodbmgr.Core break; case ".json": - FileStream jrs = new FileStream(file, FileMode.Open, FileAccess.Read); - TextReader jr = new StreamReader(jrs); - JsonSerializer js = new JsonSerializer(); + var jrs = new FileStream(file, FileMode.Open, FileAccess.Read); + TextReader jr = new StreamReader(jrs); + var js = new JsonSerializer(); try { - CICMMetadataType thisMetadata = - (CICMMetadataType)js.Deserialize(jr, typeof(CICMMetadataType)); + var thisMetadata = (CICMMetadataType)js.Deserialize(jr, typeof(CICMMetadataType)); + if(thisMetadata.Architectures != null) architectures.AddRange(thisMetadata.Architectures); - if(thisMetadata.Barcodes != null) barcodes.AddRange(thisMetadata.Barcodes); - if(thisMetadata.BlockMedia != null) disks.AddRange(thisMetadata.BlockMedia); - if(thisMetadata.Categories != null) categories.AddRange(thisMetadata.Categories); - if(thisMetadata.Keywords != null) keywords.AddRange(thisMetadata.Keywords); - if(thisMetadata.Languages != null) languages.AddRange(thisMetadata.Languages); - if(thisMetadata.OpticalDisc != null) discs.AddRange(thisMetadata.OpticalDisc); + + if(thisMetadata.Barcodes != null) + barcodes.AddRange(thisMetadata.Barcodes); + + if(thisMetadata.BlockMedia != null) + disks.AddRange(thisMetadata.BlockMedia); + + if(thisMetadata.Categories != null) + categories.AddRange(thisMetadata.Categories); + + if(thisMetadata.Keywords != null) + keywords.AddRange(thisMetadata.Keywords); + + if(thisMetadata.Languages != null) + languages.AddRange(thisMetadata.Languages); + + if(thisMetadata.OpticalDisc != null) + discs.AddRange(thisMetadata.OpticalDisc); + if(thisMetadata.Subcategories != null) subcategories.AddRange(thisMetadata.Subcategories); - if(thisMetadata.Systems != null) systems.AddRange(thisMetadata.Systems); - if(thisMetadata.Author != null) authors.AddRange(thisMetadata.Author); - if(thisMetadata.Developer != null) developers.AddRange(thisMetadata.Developer); - if(thisMetadata.Performer != null) performers.AddRange(thisMetadata.Performer); - if(thisMetadata.Publisher != null) publishers.AddRange(thisMetadata.Publisher); + + if(thisMetadata.Systems != null) + systems.AddRange(thisMetadata.Systems); + + if(thisMetadata.Author != null) + authors.AddRange(thisMetadata.Author); + + if(thisMetadata.Developer != null) + developers.AddRange(thisMetadata.Developer); + + if(thisMetadata.Performer != null) + performers.AddRange(thisMetadata.Performer); + + if(thisMetadata.Publisher != null) + publishers.AddRange(thisMetadata.Publisher); + if(string.IsNullOrWhiteSpace(metadataName) && - !string.IsNullOrWhiteSpace(thisMetadata.Name)) metadataName = thisMetadata.Name; + !string.IsNullOrWhiteSpace(thisMetadata.Name)) + metadataName = thisMetadata.Name; + if(string.IsNullOrWhiteSpace(metadataPartNo) && !string.IsNullOrWhiteSpace(thisMetadata.PartNumber)) metadataPartNo = thisMetadata.PartNumber; + if(string.IsNullOrWhiteSpace(metadataSerial) && !string.IsNullOrWhiteSpace(thisMetadata.SerialNumber)) metadataSerial = thisMetadata.SerialNumber; + if(string.IsNullOrWhiteSpace(metadataVersion) && !string.IsNullOrWhiteSpace(thisMetadata.Version)) metadataVersion = thisMetadata.Version; + if(thisMetadata.ReleaseDateSpecified) if(thisMetadata.ReleaseDate > releaseDate) { @@ -325,20 +417,35 @@ namespace apprepodbmgr.Core releaseType = thisMetadata.ReleaseType; } - if(thisMetadata.Magazine != null) magazines.AddRange(thisMetadata.Magazine); - if(thisMetadata.Book != null) books.AddRange(thisMetadata.Book); + if(thisMetadata.Magazine != null) + magazines.AddRange(thisMetadata.Magazine); + + if(thisMetadata.Book != null) + books.AddRange(thisMetadata.Book); + if(thisMetadata.RequiredOperatingSystems != null) requiredOses.AddRange(thisMetadata.RequiredOperatingSystems); - if(thisMetadata.UserManual != null) usermanuals.AddRange(thisMetadata.UserManual); - if(thisMetadata.Advertisement != null) adverts.AddRange(thisMetadata.Advertisement); - if(thisMetadata.LinearMedia != null) linearmedias.AddRange(thisMetadata.LinearMedia); - if(thisMetadata.PCICard != null) pcis.AddRange(thisMetadata.PCICard); - if(thisMetadata.AudioMedia != null) audiomedias.AddRange(thisMetadata.AudioMedia); + + if(thisMetadata.UserManual != null) + usermanuals.AddRange(thisMetadata.UserManual); + + if(thisMetadata.Advertisement != null) + adverts.AddRange(thisMetadata.Advertisement); + + if(thisMetadata.LinearMedia != null) + linearmedias.AddRange(thisMetadata.LinearMedia); + + if(thisMetadata.PCICard != null) + pcis.AddRange(thisMetadata.PCICard); + + if(thisMetadata.AudioMedia != null) + audiomedias.AddRange(thisMetadata.AudioMedia); foundMetadata = true; string metadataFileWithoutExtension = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)); + alreadyMetadata.Add(metadataFileWithoutExtension + ".xml"); alreadyMetadata.Add(metadataFileWithoutExtension + ".xmL"); alreadyMetadata.Add(metadataFileWithoutExtension + ".xMl"); @@ -366,6 +473,7 @@ namespace apprepodbmgr.Core jr.Close(); jrs.Close(); + continue; } catch(JsonException) @@ -411,58 +519,75 @@ namespace apprepodbmgr.Core case "leggi": case "lesidmig": Context.Readmes.Add(file); + break; } if((Path.GetExtension(file).ToLowerInvariant() == ".nfo" || Path.GetExtension(file).ToLowerInvariant() == ".diz" || Path.GetExtension(file).ToLowerInvariant() == ".txt") && - !Context.Readmes.Contains(file)) Context.Readmes.Add(file); + !Context.Readmes.Contains(file)) + Context.Readmes.Add(file); - FileStream exeStream = new FileStream(file, FileMode.Open, FileAccess.Read); - // Catch all exceptions in this block to prevent a failure in libexeinfo to crash us whole + var exeStream = new FileStream(file, FileMode.Open, FileAccess.Read); + + // Catch all exceptions in this block to prevent a failure in libexeinfo to crash us whole try { - if(AtariST.Identify(exeStream) || COFF.Identify(exeStream) || ELF.Identify(exeStream) || - Geos.Identify(exeStream) || LX.Identify(exeStream) || MZ.Identify(exeStream) || - NE.Identify(exeStream) || PE.Identify(exeStream)) Context.Executables.Add(file); + if(AtariST.Identify(exeStream) || + COFF.Identify(exeStream) || + ELF.Identify(exeStream) || + Geos.Identify(exeStream) || + LX.Identify(exeStream) || + MZ.Identify(exeStream) || + NE.Identify(exeStream) || + PE.Identify(exeStream)) + Context.Executables.Add(file); } catch(Exception ex) { Console.WriteLine("Exception in libexeinfo wjem processing file {0}:", file); - Console.WriteLine("Exception: {0}", ex.Message); - Console.WriteLine("Source: {0}", ex.Source); - Console.WriteLine("Stack trace: {0}", ex.StackTrace); - Console.WriteLine("Please report the exception and accompany the file to https://github.com/claunia/libexeinfo"); + Console.WriteLine("Exception: {0}", ex.Message); + Console.WriteLine("Source: {0}", ex.Source); + Console.WriteLine("Stack trace: {0}", ex.StackTrace); + + Console. + WriteLine("Please report the exception and accompany the file to https://github.com/claunia/libexeinfo"); + Console.WriteLine("Continuing..."); } exeStream.Close(); - string filesPath; - FileInfo fi = new FileInfo(file); + string filesPath; + var fi = new FileInfo(file); - if(!string.IsNullOrEmpty(Context.TmpFolder) && Directory.Exists(Context.TmpFolder)) - filesPath = Context.TmpFolder; - else filesPath = Context.Path; + if(!string.IsNullOrEmpty(Context.TmpFolder) && + Directory.Exists(Context.TmpFolder)) + filesPath = Context.TmpFolder; + else + filesPath = Context.Path; string relpath = file.Substring(filesPath.Length + 1); UpdateProgress?.Invoke($"Hashing file {counter} of {Context.Files.Count}", null, counter, Context.Files.Count); - FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); - byte[] dataBuffer; - Sha256Context sha256Context = new Sha256Context(); + var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); + + byte[] dataBuffer; + var sha256Context = new Sha256Context(); if(fileStream.Length > BUFFER_SIZE) { long offset; long remainder = fileStream.Length % BUFFER_SIZE; + for(offset = 0; offset < fileStream.Length - remainder; offset += (int)BUFFER_SIZE) { UpdateProgress2?.Invoke($"{offset / (double)fileStream.Length:P}", relpath, offset, fileStream.Length); + dataBuffer = new byte[BUFFER_SIZE]; fileStream.Read(dataBuffer, 0, (int)BUFFER_SIZE); sha256Context.Update(dataBuffer); @@ -470,6 +595,7 @@ namespace apprepodbmgr.Core UpdateProgress2?.Invoke($"{offset / (double)fileStream.Length:P}", relpath, offset, fileStream.Length); + dataBuffer = new byte[remainder]; fileStream.Read(dataBuffer, 0, (int)remainder); sha256Context.Update(dataBuffer); @@ -485,7 +611,7 @@ namespace apprepodbmgr.Core fileStream.Close(); string hash = Stringify(sha256Context.Final()); - DbAppFile dbFile = new DbAppFile + var dbFile = new DbAppFile { Attributes = fi.Attributes, CreationTimeUtc = fi.CreationTimeUtc, @@ -504,27 +630,33 @@ namespace apprepodbmgr.Core Context.Hashes.Add(relpath, dbFile); counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.HashFiles(): Took {0} seconds to hash all files", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif counter = 1; + foreach(string folder in Context.Folders) { - string filesPath; - DirectoryInfo di = new DirectoryInfo(folder); + string filesPath; + var di = new DirectoryInfo(folder); - if(!string.IsNullOrEmpty(Context.TmpFolder) && Directory.Exists(Context.TmpFolder)) - filesPath = Context.TmpFolder; - else filesPath = Context.Path; + if(!string.IsNullOrEmpty(Context.TmpFolder) && + Directory.Exists(Context.TmpFolder)) + filesPath = Context.TmpFolder; + else + filesPath = Context.Path; string relpath = folder.Substring(filesPath.Length + 1); + UpdateProgress?.Invoke($"Checking folder {counter} of {Context.Folders.Count}", null, counter, Context.Folders.Count); - DbFolder dbFolder = new DbFolder + var dbFolder = new DbFolder { Attributes = di.Attributes, CreationTimeUtc = di.CreationTimeUtc, @@ -536,20 +668,25 @@ namespace apprepodbmgr.Core Context.FoldersDict.Add(relpath, dbFolder); counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.HashFiles(): Took {0} seconds to iterate all folders", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif counter = 2; + foreach(string symlink in Context.Symlinks) { string filesPath; - if(!string.IsNullOrEmpty(Context.TmpFolder) && Directory.Exists(Context.TmpFolder)) - filesPath = Context.TmpFolder; - else filesPath = Context.Path; + if(!string.IsNullOrEmpty(Context.TmpFolder) && + Directory.Exists(Context.TmpFolder)) + filesPath = Context.TmpFolder; + else + filesPath = Context.Path; string relpath = symlink.Substring(filesPath.Length + 1); @@ -557,38 +694,66 @@ namespace apprepodbmgr.Core Context.Symlinks.Count); string target = Symlinks.ReadLink(symlink); + if(target == null) { Failed?.Invoke($"Could not resolve symbolic link at {relpath}, not continuing."); + return; } Context.SymlinksDict.Add(relpath, target); counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.HashFiles(): Took {0} seconds to resolve all symbolic links", stopwatch.Elapsed.TotalSeconds); - #endif + #endif if(foundMetadata) { Context.Metadata = new CICMMetadataType(); - if(architectures.Count > 0) Context.Metadata.Architectures = architectures.Distinct().ToArray(); - if(authors.Count > 0) Context.Metadata.Author = authors.Distinct().ToArray(); + + if(architectures.Count > 0) + Context.Metadata.Architectures = architectures.Distinct().ToArray(); + + if(authors.Count > 0) + Context.Metadata.Author = authors.Distinct().ToArray(); + // TODO: Check for uniqueness - if(barcodes.Count > 0) Context.Metadata.Barcodes = barcodes.ToArray(); - if(disks.Count > 0) Context.Metadata.BlockMedia = disks.ToArray(); - if(categories.Count > 0) Context.Metadata.Categories = categories.Distinct().ToArray(); - if(developers.Count > 0) Context.Metadata.Developer = developers.Distinct().ToArray(); - if(keywords.Count > 0) Context.Metadata.Keywords = keywords.Distinct().ToArray(); - if(languages.Count > 0) Context.Metadata.Languages = languages.Distinct().ToArray(); + if(barcodes.Count > 0) + Context.Metadata.Barcodes = barcodes.ToArray(); + + if(disks.Count > 0) + Context.Metadata.BlockMedia = disks.ToArray(); + + if(categories.Count > 0) + Context.Metadata.Categories = categories.Distinct().ToArray(); + + if(developers.Count > 0) + Context.Metadata.Developer = developers.Distinct().ToArray(); + + if(keywords.Count > 0) + Context.Metadata.Keywords = keywords.Distinct().ToArray(); + + if(languages.Count > 0) + Context.Metadata.Languages = languages.Distinct().ToArray(); + Context.Metadata.Name = metadataName; - if(discs.Count > 0) Context.Metadata.OpticalDisc = discs.ToArray(); + + if(discs.Count > 0) + Context.Metadata.OpticalDisc = discs.ToArray(); + Context.Metadata.PartNumber = metadataPartNo; - if(performers.Count > 0) Context.Metadata.Performer = performers.Distinct().ToArray(); - if(publishers.Count > 0) Context.Metadata.Publisher = publishers.Distinct().ToArray(); + + if(performers.Count > 0) + Context.Metadata.Performer = performers.Distinct().ToArray(); + + if(publishers.Count > 0) + Context.Metadata.Publisher = publishers.Distinct().ToArray(); + if(releaseDateSpecified) { Context.Metadata.ReleaseDate = releaseDate; @@ -602,8 +767,13 @@ namespace apprepodbmgr.Core } Context.Metadata.SerialNumber = metadataSerial; - if(subcategories.Count > 0) Context.Metadata.Subcategories = subcategories.Distinct().ToArray(); - if(systems.Count > 0) Context.Metadata.Systems = systems.Distinct().ToArray(); + + if(subcategories.Count > 0) + Context.Metadata.Subcategories = subcategories.Distinct().ToArray(); + + if(systems.Count > 0) + Context.Metadata.Systems = systems.Distinct().ToArray(); + Context.Metadata.Version = metadataVersion; Context.Metadata.Magazine = magazines.ToArray(); Context.Metadata.Book = books.ToArray(); @@ -614,21 +784,24 @@ namespace apprepodbmgr.Core Context.Metadata.PCICard = pcis.ToArray(); Context.Metadata.AudioMedia = audiomedias.ToArray(); - foreach(string metadataFile in alreadyMetadata) Context.Files.Remove(metadataFile); + foreach(string metadataFile in alreadyMetadata) + Context.Files.Remove(metadataFile); } - else Context.Metadata = null; + else + Context.Metadata = null; Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -636,12 +809,13 @@ namespace apprepodbmgr.Core { try { - if(!Directory.Exists(Context.TmpFolder)) return; + if(!Directory.Exists(Context.TmpFolder)) + return; Directory.Delete(Context.TmpFolder, true); Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(IOException) { // Could not delete temporary files, do not crash. @@ -649,12 +823,13 @@ namespace apprepodbmgr.Core } catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -665,27 +840,30 @@ namespace apprepodbmgr.Core if(!File.Exists(Context.Path)) { Failed?.Invoke("Specified file cannot be found"); + return; } if(string.IsNullOrWhiteSpace(Context.TmpFolder)) { Failed?.Invoke("Destination cannot be empty"); + return; } if(Directory.Exists(Context.TmpFolder)) { Failed?.Invoke("Destination cannot be a folder"); + return; } - FileStream inFs = new FileStream(Context.Path, FileMode.Open, FileAccess.Read); - FileStream outFs = new FileStream(Context.TmpFolder, FileMode.Create, FileAccess.Write); + var inFs = new FileStream(Context.Path, FileMode.Open, FileAccess.Read); + var outFs = new FileStream(Context.TmpFolder, FileMode.Create, FileAccess.Write); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif byte[] buffer = new byte[BUFFER_SIZE]; while(inFs.Position + BUFFER_SIZE <= inFs.Length) @@ -698,6 +876,7 @@ namespace apprepodbmgr.Core } buffer = new byte[inFs.Length - inFs.Position]; + UpdateProgress?.Invoke("Copying file...", $"{inFs.Position} / {inFs.Length} bytes", inFs.Position, inFs.Length); @@ -706,22 +885,23 @@ namespace apprepodbmgr.Core inFs.Close(); outFs.Close(); - #if DEBUG + #if DEBUG stopwatch.Stop(); Console.WriteLine("Core.CopyFile(): Took {0} seconds to copy file", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -732,18 +912,21 @@ namespace apprepodbmgr.Core if(string.IsNullOrWhiteSpace(Context.Path)) { Failed?.Invoke("Destination cannot be empty"); + return; } if(File.Exists(Context.Path)) { Failed?.Invoke("Destination cannot be a file"); + return; } if(Context.DbInfo.Id == 0) { Failed?.Invoke("Operating system must be set"); + return; } @@ -770,6 +953,7 @@ namespace apprepodbmgr.Core if(!symlinksSupported) { Failed?.Invoke("Symbolic links cannot be created on this platform."); + return; } @@ -778,10 +962,11 @@ namespace apprepodbmgr.Core UpdateProgress?.Invoke("", "Creating folders...", 4, 100); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif long counter = 0; + foreach(DbFolder folder in folders) { UpdateProgress2?.Invoke("", folder.Path, counter, folders.Count); @@ -794,18 +979,20 @@ namespace apprepodbmgr.Core counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.SaveAs(): Took {0} seconds to create all folders", stopwatch.Elapsed.TotalSeconds); - #endif + #endif UpdateProgress?.Invoke("", "Creating symbolic links...", 4, 100); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif counter = 0; + foreach(KeyValuePair kvp in symlinks) { UpdateProgress2?.Invoke("", kvp.Key, counter, folders.Count); @@ -813,17 +1000,19 @@ namespace apprepodbmgr.Core Symlinks.Symlink(kvp.Value, kvp.Key); counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.SaveAs(): Took {0} seconds to create all symbolic links", stopwatch.Elapsed.TotalSeconds); - #endif + #endif - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif counter = 4; + foreach(DbAppFile file in files) { UpdateProgress?.Invoke("", $"Creating {file.Path}...", counter, 4 + files.Count); @@ -841,6 +1030,7 @@ namespace apprepodbmgr.Core file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".gz"); + algorithm = AlgoEnum.GZip; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -852,6 +1042,7 @@ namespace apprepodbmgr.Core file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".bz2"); + algorithm = AlgoEnum.BZip2; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -863,6 +1054,7 @@ namespace apprepodbmgr.Core file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lzma"); + algorithm = AlgoEnum.LZMA; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -874,36 +1066,43 @@ namespace apprepodbmgr.Core file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lz"); + algorithm = AlgoEnum.LZip; } else { Failed?.Invoke($"Cannot find file with hash {file.Sha256} in the repository"); + return; } - FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); - FileStream outFs = new FileStream(Path.Combine(Context.Path, file.Path), FileMode.CreateNew, - FileAccess.Write); + var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); + + var outFs = new FileStream(Path.Combine(Context.Path, file.Path), FileMode.CreateNew, + FileAccess.Write); long inLength = inFs.Length; - + switch(algorithm) { case AlgoEnum.GZip: zStream = new GZipStream(inFs, CompressionMode.Decompress); + break; case AlgoEnum.BZip2: zStream = new BZip2Stream(inFs, CompressionMode.Decompress); + break; case AlgoEnum.LZMA: byte[] properties = new byte[5]; inFs.Read(properties, 0, 5); inFs.Seek(8, SeekOrigin.Current); zStream = new LzmaStream(properties, inFs); + break; case AlgoEnum.LZip: zStream = new LZipStream(inFs, CompressionMode.Decompress); + break; } @@ -919,6 +1118,7 @@ namespace apprepodbmgr.Core } buffer = new byte[file.Length - outFs.Position]; + UpdateProgress2?.Invoke($"{outFs.Position / (double)file.Length:P}", $"{outFs.Position} / {file.Length} bytes", outFs.Position, file.Length); @@ -931,7 +1131,7 @@ namespace apprepodbmgr.Core zStream.Close(); outFs.Close(); - FileInfo fi = new FileInfo(Path.Combine(Context.Path, file.Path)) + var fi = new FileInfo(Path.Combine(Context.Path, file.Path)) { Attributes = file.Attributes, CreationTimeUtc = file.CreationTimeUtc, @@ -941,23 +1141,25 @@ namespace apprepodbmgr.Core counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.SaveAs(): Took {0} seconds to create all files", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished?.Invoke(); } - catch(ThreadAbortException) { } + catch(ThreadAbortException) {} catch(Exception ex) { - if(Debugger.IsAttached) throw; + if(Debugger.IsAttached) + throw; Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } @@ -970,12 +1172,13 @@ namespace apprepodbmgr.Core List filesPage; List allFiles = new List(); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif while(dbCore.DbOps.GetFiles(out filesPage, offset, page)) { - if(filesPage.Count == 0) break; + if(filesPage.Count == 0) + break; UpdateProgress?.Invoke(null, $"Loaded file {offset} of {count}", (long)offset, (long)count); @@ -983,41 +1186,44 @@ namespace apprepodbmgr.Core offset += page; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CleanFiles(): Took {0} seconds to get all files from the database", stopwatch.Elapsed.TotalSeconds); - #endif + #endif filesPage = null; UpdateProgress?.Invoke(null, "Getting OSes from the database", 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif dbCore.DbOps.GetAllApps(out List apps); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CleanFiles(): Took {0} seconds to get OSes from database", stopwatch.Elapsed.TotalSeconds); - #endif + #endif List orphanFiles = new List(); - #if DEBUG + #if DEBUG stopwatch.Restart(); - Stopwatch stopwatch2 = new Stopwatch(); - #endif + var stopwatch2 = new Stopwatch(); + #endif int counterF = 0; + foreach(DbFile file in allFiles) { UpdateProgress?.Invoke(null, $"Checking file {counterF} of {allFiles.Count}", counterF, allFiles.Count); bool fileExists = false; int counterO = 0; - #if DEBUG + #if DEBUG stopwatch2.Restart(); - #endif + #endif foreach(DbEntry app in apps) { UpdateProgress2?.Invoke(null, $"Checking OS {counterO} of {apps.Count}", counterO, apps.Count); @@ -1025,32 +1231,36 @@ namespace apprepodbmgr.Core if(dbCore.DbOps.ExistsFileInApp(file.Sha256, app.Id)) { fileExists = true; + break; } counterO++; } - #if DEBUG + #if DEBUG stopwatch2.Stop(); + Console.WriteLine("Core.CleanFiles(): Took {0} seconds to check file in all applications", stopwatch2.Elapsed.TotalSeconds); - #endif + #endif - if(!fileExists) orphanFiles.Add(file.Sha256); + if(!fileExists) + orphanFiles.Add(file.Sha256); counterF++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); Console.WriteLine("Core.CleanFiles(): Took {0} seconds to check all files", stopwatch.Elapsed.TotalSeconds); - #endif + #endif UpdateProgress2?.Invoke(null, null, 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif counterF = 0; + foreach(string hash in orphanFiles) { UpdateProgress?.Invoke(null, $"Deleting file {counterF} of {orphanFiles.Count} from database", counterF, @@ -1059,58 +1269,70 @@ namespace apprepodbmgr.Core dbCore.DbOps.DeleteFile(hash); counterF++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CleanFiles(): Took {0} seconds to remove all orphan files from database", stopwatch.Elapsed.TotalSeconds); - #endif + #endif UpdateProgress?.Invoke(null, "Listing files in repository", 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif List repoFiles = new List(Directory.EnumerateFiles(Settings.Current.RepositoryPath, "*", SearchOption.AllDirectories)); + repoFiles.Sort(); - #if DEBUG + #if DEBUG stopwatch.Stop(); Console.WriteLine("Core.CleanFiles(): Took {0} seconds to find all files", stopwatch.Elapsed.TotalSeconds); stopwatch.Restart(); - #endif + #endif counterF = 0; List filesToDelete = new List(); + foreach(string file in repoFiles) { UpdateProgress?.Invoke(null, $"Checking file {counterF} of {repoFiles.Count} from repository", counterF, repoFiles.Count); // Allow database to be inside repo - if(file == Settings.Current.DatabasePath) continue; + if(file == Settings.Current.DatabasePath) + continue; if(Path.GetExtension(file)?.ToLowerInvariant() == ".xml" || Path.GetExtension(file)?.ToLowerInvariant() == ".json") { - if(!dbCore.DbOps.ExistsOs(Path.GetFileNameWithoutExtension(file))) filesToDelete.Add(file); + if(!dbCore.DbOps.ExistsOs(Path.GetFileNameWithoutExtension(file))) + filesToDelete.Add(file); } - else if(!dbCore.DbOps.ExistsFile(Path.GetFileNameWithoutExtension(file))) filesToDelete.Add(file); + else if(!dbCore.DbOps.ExistsFile(Path.GetFileNameWithoutExtension(file))) + filesToDelete.Add(file); counterF++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CleanFiles(): Took {0} seconds to check all repository files", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); - #endif + #endif counterF = 0; + foreach(string file in filesToDelete) { UpdateProgress?.Invoke(null, $"Deleting file {counterF} of {filesToDelete.Count} from repository", counterF, filesToDelete.Count); - try { File.Delete(file); } + try + { + File.Delete(file); + } #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body catch #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body @@ -1120,11 +1342,12 @@ namespace apprepodbmgr.Core counterF++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.CleanFiles(): Took {0} seconds to delete all orphan files", stopwatch.Elapsed.TotalSeconds); - #endif + #endif Finished?.Invoke(); } diff --git a/apprepodbmgr.Core/Workers/Miscellaneous.cs b/apprepodbmgr.Core/Workers/Miscellaneous.cs index 2e62ca3..d5f4f5d 100644 --- a/apprepodbmgr.Core/Workers/Miscellaneous.cs +++ b/apprepodbmgr.Core/Workers/Miscellaneous.cs @@ -40,15 +40,16 @@ namespace apprepodbmgr.Core static int zipCounter; static string zipCurrentEntryName; - #if DEBUG - static Stopwatch stopwatch = new Stopwatch(); - #endif + #if DEBUG + static readonly Stopwatch stopwatch = new Stopwatch(); + #endif static string Stringify(byte[] hash) { - StringBuilder hashOutput = new StringBuilder(); + var hashOutput = new StringBuilder(); - foreach(byte h in hash) hashOutput.Append(h.ToString("x2")); + foreach(byte h in hash) + hashOutput.Append(h.ToString("x2")); return hashOutput.ToString(); } @@ -58,6 +59,7 @@ namespace apprepodbmgr.Core if(string.IsNullOrWhiteSpace(Settings.Current.UnArchiverPath)) { Failed?.Invoke("unar path is not set."); + return; } @@ -71,12 +73,14 @@ namespace apprepodbmgr.Core if(!File.Exists(unarPath)) { Failed?.Invoke($"Cannot find unar executable at {unarPath}."); + return; } if(!File.Exists(lsarPath)) { Failed?.Invoke("Cannot find unar executable."); + return; } @@ -84,7 +88,7 @@ namespace apprepodbmgr.Core try { - Process unarProcess = new Process + var unarProcess = new Process { StartInfo = { @@ -94,6 +98,7 @@ namespace apprepodbmgr.Core UseShellExecute = false } }; + unarProcess.Start(); unarProcess.WaitForExit(); unarOut = unarProcess.StandardOutput.ReadToEnd(); @@ -101,12 +106,13 @@ namespace apprepodbmgr.Core catch { Failed?.Invoke("Cannot run unar."); + return; } try { - Process lsarProcess = new Process + var lsarProcess = new Process { StartInfo = { @@ -116,6 +122,7 @@ namespace apprepodbmgr.Core UseShellExecute = false } }; + lsarProcess.Start(); lsarProcess.WaitForExit(); lsarOut = lsarProcess.StandardOutput.ReadToEnd(); @@ -123,22 +130,25 @@ namespace apprepodbmgr.Core catch { Failed?.Invoke("Cannot run lsar."); + return; } if(!unarOut.StartsWith("unar ", StringComparison.CurrentCulture)) { Failed?.Invoke("Not the correct unar executable"); + return; } if(!lsarOut.StartsWith("lsar ", StringComparison.CurrentCulture)) { Failed?.Invoke("Not the correct unar executable"); + return; } - Process versionProcess = new Process + var versionProcess = new Process { StartInfo = { @@ -149,6 +159,7 @@ namespace apprepodbmgr.Core Arguments = "-v" } }; + versionProcess.Start(); versionProcess.WaitForExit(); diff --git a/apprepodbmgr.Core/Workers/VirusTotal.cs b/apprepodbmgr.Core/Workers/VirusTotal.cs index 98d5329..d2d9234 100644 --- a/apprepodbmgr.Core/Workers/VirusTotal.cs +++ b/apprepodbmgr.Core/Workers/VirusTotal.cs @@ -55,7 +55,8 @@ namespace apprepodbmgr.Core { Task.Run(async () => { - vt = new VirusTotal(key); + vt = new VirusTotal(key); + report = await vt.GetFileReportAsync("b82758fc5f737a58078d3c60e2798a70d895443a86aa39adf52dec70e98c2bed"); }).Wait(); @@ -63,6 +64,7 @@ namespace apprepodbmgr.Core catch(Exception ex) { Failed?.Invoke(ex.InnerException?.Message); + return false; } @@ -78,7 +80,8 @@ namespace apprepodbmgr.Core { Task.Run(async () => { - vt = new VirusTotal(key); + vt = new VirusTotal(key); + report = await vt.GetFileReportAsync("b82758fc5f737a58078d3c60e2798a70d895443a86aa39adf52dec70e98c2bed"); }).Wait(); @@ -86,13 +89,17 @@ namespace apprepodbmgr.Core catch(Exception ex) { Failed?.Invoke(ex.InnerException?.Message); + return false; } - if(report == null || report.MD5 != "0bf60adb1435639a42b490e7e80d25c7") return false; + if(report == null || + report.MD5 != "0bf60adb1435639a42b490e7e80d25c7") + return false; vTotal = vt; Context.VirusTotalEnabled = true; + return true; } @@ -103,41 +110,50 @@ namespace apprepodbmgr.Core if(!Context.VirusTotalEnabled) { Failed?.Invoke("VirusTotal is not usable"); + return; } - if(vTotal == null) Failed?.Invoke("VirusTotal is not initalized"); + if(vTotal == null) + Failed?.Invoke("VirusTotal is not initalized"); FileReport fResult = null; UpdateProgress?.Invoke("Requesting existing report to VirusTotal", null, 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif - Task.Run(async () => { fResult = await vTotal.GetFileReportAsync(file.Sha256); }).Wait(); - #if DEBUG + #endif + Task.Run(async () => + { + fResult = await vTotal.GetFileReportAsync(file.Sha256); + }).Wait(); + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.VirusTotalFileFromRepo({0}): VirusTotal took {1} seconds to answer for SHA256 request", file, stopwatch.Elapsed.TotalSeconds); - #endif + #endif if(fResult.ResponseCode == FileReportResponseCode.NotPresent) { Failed?.Invoke(fResult.VerboseMsg); + return; } if(fResult.ResponseCode != FileReportResponseCode.Queued) { - if(fResult.ResponseCode == FileReportResponseCode.Present) + if(fResult.ResponseCode == FileReportResponseCode.Present) if(fResult.Positives > 0) { file.HasVirus = true; + if(fResult.Scans != null) foreach(KeyValuePair engine in fResult.Scans) { - if(!engine.Value.Detected) continue; + if(!engine.Value.Detected) + continue; file.Virus = engine.Value.Result; file.VirusTotalTime = engine.Value.Update; @@ -175,6 +191,7 @@ namespace apprepodbmgr.Core file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".gz"); + algorithm = AlgoEnum.GZip; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -186,6 +203,7 @@ namespace apprepodbmgr.Core file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".bz2"); + algorithm = AlgoEnum.BZip2; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -197,6 +215,7 @@ namespace apprepodbmgr.Core file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lzma"); + algorithm = AlgoEnum.LZMA; } else if(File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(), @@ -208,77 +227,89 @@ namespace apprepodbmgr.Core file.Sha256[1].ToString(), file.Sha256[2].ToString(), file.Sha256[3].ToString(), file.Sha256[4].ToString(), file.Sha256 + ".lz"); + algorithm = AlgoEnum.LZip; } else { Failed?.Invoke($"Cannot find file with hash {file.Sha256} in the repository"); + return; } UpdateProgress?.Invoke("Uncompressing file...", null, 0, 0); - FileStream inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); - Stream zStream = null; + var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); + Stream zStream = null; switch(algorithm) { case AlgoEnum.GZip: zStream = new GZipStream(inFs, CompressionMode.Decompress); + break; case AlgoEnum.BZip2: zStream = new BZip2Stream(inFs, CompressionMode.Decompress); + break; case AlgoEnum.LZMA: byte[] properties = new byte[5]; inFs.Read(properties, 0, 5); inFs.Seek(8, SeekOrigin.Current); zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length); + break; case AlgoEnum.LZip: zStream = new LZipStream(inFs, CompressionMode.Decompress); + break; } ScanResult sResult = null; - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif + // Cannot use zStream directly, VirusTotal.NET requests the size *sigh* - string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName()); - FileStream outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite); + string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName()); + var outFs = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite); zStream?.CopyTo(outFs); zStream?.Close(); outFs.Seek(0, SeekOrigin.Begin); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.VirusTotalFileFromRepo({0}): Uncompressing took {1} seconds", file, stopwatch.Elapsed.TotalSeconds); - #endif + #endif UpdateProgress?.Invoke("Uploading file to VirusTotal...", null, 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif Task.Run(async () => { sResult = await vTotal.ScanFileAsync(outFs, file.Sha256); // Keep filename private, sorry! }).Wait(); - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.VirusTotalFileFromRepo({0}): Upload to VirusTotal took {1} seconds", file, stopwatch.Elapsed.TotalSeconds); - #endif + #endif outFs.Close(); File.Delete(tmpFile); - if(sResult == null || sResult.ResponseCode == ScanFileResponseCode.Error) + if(sResult == null || + sResult.ResponseCode == ScanFileResponseCode.Error) { - if(sResult == null) Failed?.Invoke("Cannot send file to VirusTotal"); - else Failed(sResult.VerboseMsg); + if(sResult == null) + Failed?.Invoke("Cannot send file to VirusTotal"); + else + Failed(sResult.VerboseMsg); return; } @@ -286,47 +317,60 @@ namespace apprepodbmgr.Core // Seems that we are faster than them, getting a lot of "not queued" responses... Thread.Sleep(2500); - Task.Run(async () => { fResult = await vTotal.GetFileReportAsync(file.Sha256); }).Wait(); + Task.Run(async () => + { + fResult = await vTotal.GetFileReportAsync(file.Sha256); + }).Wait(); } UpdateProgress?.Invoke("Waiting for VirusTotal analysis...", null, 0, 0); - #if DEBUG + #if DEBUG stopwatch.Restart(); - #endif + #endif int counter = 0; + while(fResult.ResponseCode == FileReportResponseCode.Queued) { // Timeout... - if(counter == 10) break; + if(counter == 10) + break; // Wait 15 seconds so we fall in the 4 requests/minute Thread.Sleep(15000); - Task.Run(async () => { fResult = await vTotal.GetFileReportAsync(file.Sha256); }).Wait(); + Task.Run(async () => + { + fResult = await vTotal.GetFileReportAsync(file.Sha256); + }).Wait(); counter++; } - #if DEBUG + #if DEBUG stopwatch.Stop(); + Console.WriteLine("Core.VirusTotalFileFromRepo({0}): VirusTotal took {1} seconds to do the analysis", file, stopwatch.Elapsed.TotalSeconds); - #endif + #endif if(fResult.ResponseCode != FileReportResponseCode.Present) { Failed?.Invoke(fResult.VerboseMsg); + return; } if(fResult.Positives > 0) { file.HasVirus = true; - if(fResult.Scans == null) return; + + if(fResult.Scans == null) + return; foreach(KeyValuePair engine in fResult.Scans) { - if(!engine.Value.Detected) continue; + if(!engine.Value.Detected) + continue; file.Virus = engine.Value.Result; file.VirusTotalTime = engine.Value.Update; @@ -353,9 +397,9 @@ namespace apprepodbmgr.Core catch(Exception ex) { Failed?.Invoke($"Exception {ex.InnerException.Message} when calling VirusTotal"); - #if DEBUG + #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); - #endif + #endif } } } diff --git a/apprepodbmgr.Eto.Desktop/Program.cs b/apprepodbmgr.Eto.Desktop/Program.cs index f588c5f..0b187b3 100644 --- a/apprepodbmgr.Eto.Desktop/Program.cs +++ b/apprepodbmgr.Eto.Desktop/Program.cs @@ -40,9 +40,12 @@ namespace apprepodbmgr.Eto.Desktop { Settings.LoadSettings(); Context.CheckUnar(); + if(Settings.Current.UseAntivirus) { - if(Settings.Current.UseClamd) Workers.InitClamd(); + if(Settings.Current.UseClamd) + Workers.InitClamd(); + if(Settings.Current.UseVirusTotal) Context.VirusTotalEnabled = Workers.InitVirusTotal(Settings.Current.VirusTotalKey); } @@ -52,4 +55,4 @@ namespace apprepodbmgr.Eto.Desktop new Application(Platform.Detect).Run(new frmMain()); } } -} +} \ No newline at end of file diff --git a/apprepodbmgr.Eto/WrappersForEto.cs b/apprepodbmgr.Eto/WrappersForEto.cs index 327b5b4..8aaaa7f 100644 --- a/apprepodbmgr.Eto/WrappersForEto.cs +++ b/apprepodbmgr.Eto/WrappersForEto.cs @@ -31,139 +31,153 @@ using Schemas; namespace apprepodbmgr.Eto { - class DBEntryForEto + internal class DBEntryForEto { - DbEntry _item; + readonly DbEntry _item; - public DBEntryForEto(DbEntry item) - { - _item = item; - } + public DBEntryForEto(DbEntry item) => _item = item; public long id { - get { return _item.Id; } - set { } + get => _item.Id; + set {} } + public string developer { - get { return _item.Developer; } - set { } + get => _item.Developer; + set {} } + public string product { - get { return _item.Product; } - set { } + get => _item.Product; + set {} } + public string version { - get { return _item.Version; } - set { } + get => _item.Version; + set {} } + public string languages { - get { return _item.Languages; } - set { } + get => _item.Languages; + set {} } + public string architecture { - get { return _item.Architecture; } - set { } + get => _item.Architecture; + set {} } + public string targetos { - get { return _item.TargetOs; } - set { } + get => _item.TargetOs; + set {} } + public string format { - get { return _item.Format; } - set { } + get => _item.Format; + set {} } + public string description { - get { return _item.Description; } - set { } + get => _item.Description; + set {} } + public bool oem { - get { return _item.Oem; } - set { } + get => _item.Oem; + set {} } + public bool upgrade { - get { return _item.Upgrade; } - set { } + get => _item.Upgrade; + set {} } + public bool update { - get { return _item.Update; } - set { } + get => _item.Update; + set {} } + public bool source { - get { return _item.Source; } - set { } + get => _item.Source; + set {} } + public bool files { - get { return _item.Files; } - set { } + get => _item.Files; + set {} } + public bool Installer { - get { return _item.Installer; } - set { } + get => _item.Installer; + set {} } + public byte[] xml { - get { return _item.Xml; } - set { } + get => _item.Xml; + set {} } + public byte[] json { - get { return _item.Json; } - set { } + get => _item.Json; + set {} } + public string mdid { - get { return _item.Mdid; } - set { } + get => _item.Mdid; + set {} } public DbEntry original { - get { return _item; } - set { } + get => _item; + set {} } } - class StringEntry + internal class StringEntry { public string str { get; set; } } - class BarcodeEntry + internal class BarcodeEntry { public string code { get; set; } public BarcodeTypeType type { get; set; } } - class DiscEntry + internal class DiscEntry { public string path { get; set; } public OpticalDiscType disc { get; set; } } - class DiskEntry + internal class DiskEntry { public string path { get; set; } public BlockMediaType disk { get; set; } } - class TargetOsEntry + internal class TargetOsEntry { - public string name { get; set; } + public string name { get; set; } public string version { get; set; } } } \ No newline at end of file diff --git a/apprepodbmgr.Eto/dlgAdd.xeto.cs b/apprepodbmgr.Eto/dlgAdd.xeto.cs index f897bdd..b2932c6 100644 --- a/apprepodbmgr.Eto/dlgAdd.xeto.cs +++ b/apprepodbmgr.Eto/dlgAdd.xeto.cs @@ -47,19 +47,19 @@ namespace apprepodbmgr.Eto { public delegate void OnAddedAppDelegate(DbEntry app); - ObservableCollection appView; + readonly ObservableCollection appView; - ObservableCollection fileView; - int knownFiles; - bool stopped; - Thread thdAddFiles; - Thread thdCheckFiles; - Thread thdExtractArchive; - Thread thdFindFiles; - Thread thdHashFiles; - Thread thdOpenArchive; - Thread thdPackFiles; - Thread thdRemoveTemp; + readonly ObservableCollection fileView; + int knownFiles; + bool stopped; + Thread thdAddFiles; + Thread thdCheckFiles; + Thread thdExtractArchive; + Thread thdFindFiles; + Thread thdHashFiles; + Thread thdOpenArchive; + Thread thdPackFiles; + Thread thdRemoveTemp; public dlgAdd() { @@ -74,22 +74,37 @@ namespace apprepodbmgr.Eto treeFiles.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Path)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Path) + }, HeaderText = "Path" }); + treeFiles.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.IsCrack)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.IsCrack) + }, HeaderText = "Crack?" }); + treeFiles.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Hash)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Hash) + }, HeaderText = "SHA256" }); + treeFiles.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.Known)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.Known) + }, HeaderText = "Known?" }); @@ -106,72 +121,127 @@ namespace apprepodbmgr.Eto treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.developer)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.developer) + }, HeaderText = "Developer" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.product)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.product) + }, HeaderText = "Product" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.version)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.version) + }, HeaderText = "Version" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.languages)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.languages) + }, HeaderText = "Languages" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.architecture)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.architecture) + }, HeaderText = "Architecture" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.targetos)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.targetos) + }, HeaderText = "Target OS" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.format)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.format) + }, HeaderText = "Format" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.description)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.description) + }, HeaderText = "Description" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.oem)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.oem) + }, HeaderText = "OEM?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.upgrade)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.upgrade) + }, HeaderText = "Upgrade?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.update)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.update) + }, HeaderText = "Update?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.source)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.source) + }, HeaderText = "Source?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.files)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.files) + }, HeaderText = "Files?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.Installer)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.Installer) + }, HeaderText = "Installer?" }); @@ -179,29 +249,43 @@ namespace apprepodbmgr.Eto txtArchitecture.ToolTip = "This field contains a comma separated list of architectures the application can run on. To edit its contents use the metadata editor."; + txtDescription.ToolTip = "This field contains a free-form text description of this application."; + txtDeveloper.ToolTip = "This field contains the developer of the application. To edit its contents use the metadata editor."; + txtFormat.ToolTip = "This field is contains the name of the format of the disk images, when it is not a byte-by-byte format like .iso or .img."; + txtLanguages.ToolTip = "This field contains a comma separated list of languages the application includes. To edit its contents use the metadata editor."; + txtProduct.ToolTip = "This field contains the application name. To edit its contents use the metadata editor."; + txtTargetOs.ToolTip = "This field contains a comma separated list of operating systems this application can run on. To edit its contents use the metadata editor."; + txtVersion.ToolTip = "This field contains the application version. To edit its contents use the metadata editor."; + chkFiles.ToolTip = "If this field is checked it indicates the application is already installed."; + chkInstaller.ToolTip = "If this field is checked it indicates the application comes as an installer (one or several files), but it's not installed neither disk images."; + chkOem.ToolTip = "If this field is checked it indicates the application came bundled with hardware (aka OEM distributed)."; + chkSource.ToolTip = "If this field is checked it indicates this is the source code for the application."; + chkUpdate.ToolTip = "If this field is checked it indicates this version is a minor version update that requires a previous version of the application already installed."; + chkUpgrade.ToolTip = "If this field is checked it indicates this version is a major version upgrade that requires a previous version of the application already installed."; + txtArchitecture.ReadOnly = true; txtDeveloper.ReadOnly = true; txtLanguages.ReadOnly = true; @@ -212,22 +296,29 @@ namespace apprepodbmgr.Eto public event OnAddedAppDelegate OnAddedApp; - void UnarChangeStatus() + void UnarChangeStatus() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate { btnArchive.Enabled = Context.UnarUsable; }); - } + btnArchive.Enabled = Context.UnarUsable; + }); protected void OnDeleteEvent(object sender, CancelEventArgs e) { - if(btnStop.Visible) btnStop.PerformClick(); - if(btnClose.Enabled) btnClose.PerformClick(); + if(btnStop.Visible) + btnStop.PerformClick(); + + if(btnClose.Enabled) + btnClose.PerformClick(); } protected void OnBtnFolderClicked(object sender, EventArgs e) { - SelectFolderDialog dlgFolder = new SelectFolderDialog {Title = "Open folder"}; + var dlgFolder = new SelectFolderDialog + { + Title = "Open folder" + }; - if(dlgFolder.ShowDialog(this) != DialogResult.Ok) return; + if(dlgFolder.ShowDialog(this) != DialogResult.Ok) + return; knownFiles = 0; stopped = false; @@ -245,269 +336,290 @@ namespace apprepodbmgr.Eto thdFindFiles.Start(); } - void FindFilesFailed(string text) + void FindFilesFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(!stopped) MessageBox.Show(text, MessageBoxType.Error); - lblProgress.Visible = false; - prgProgress.Visible = false; - btnExit.Enabled = true; - btnFolder.Visible = true; - btnArchive.Visible = true; - btnStop.Visible = false; - Workers.Failed -= FindFilesFailed; - Workers.Finished -= FindFilesFinished; - thdFindFiles = null; - }); - } + if(!stopped) + MessageBox.Show(text, MessageBoxType.Error); - void FindFilesFinished() + lblProgress.Visible = false; + prgProgress.Visible = false; + btnExit.Enabled = true; + btnFolder.Visible = true; + btnArchive.Visible = true; + btnStop.Visible = false; + Workers.Failed -= FindFilesFailed; + Workers.Finished -= FindFilesFinished; + thdFindFiles = null; + }); + + void FindFilesFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - Workers.Failed -= FindFilesFailed; - Workers.Finished -= FindFilesFinished; + Workers.Failed -= FindFilesFailed; + Workers.Finished -= FindFilesFinished; - lblProgress.Visible = true; - prgProgress.Visible = true; - lblProgress2.Visible = true; - prgProgress2.Visible = true; + lblProgress.Visible = true; + prgProgress.Visible = true; + lblProgress2.Visible = true; + prgProgress2.Visible = true; - thdFindFiles = null; - thdHashFiles = new Thread(Workers.HashFiles); - Workers.Failed += HashFilesFailed; - Workers.Finished += HashFilesFinished; - Workers.UpdateProgress += UpdateProgress; - Workers.UpdateProgress2 += UpdateProgress2; - thdHashFiles.Start(); - }); - } + thdFindFiles = null; + thdHashFiles = new Thread(Workers.HashFiles); + Workers.Failed += HashFilesFailed; + Workers.Finished += HashFilesFinished; + Workers.UpdateProgress += UpdateProgress; + Workers.UpdateProgress2 += UpdateProgress2; + thdHashFiles.Start(); + }); - void HashFilesFailed(string text) + void HashFilesFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(!stopped) MessageBox.Show(text, MessageBoxType.Error); - lblProgress.Visible = false; - prgProgress.Visible = false; - lblProgress2.Visible = false; - prgProgress2.Visible = false; - Workers.Failed -= HashFilesFailed; - Workers.Finished -= HashFilesFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; - btnExit.Enabled = true; - btnFolder.Visible = true; - btnArchive.Visible = true; - btnStop.Visible = false; - thdHashFiles = null; - }); - } + if(!stopped) + MessageBox.Show(text, MessageBoxType.Error); - void HashFilesFinished() + lblProgress.Visible = false; + prgProgress.Visible = false; + lblProgress2.Visible = false; + prgProgress2.Visible = false; + Workers.Failed -= HashFilesFailed; + Workers.Finished -= HashFilesFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + btnExit.Enabled = true; + btnFolder.Visible = true; + btnArchive.Visible = true; + btnStop.Visible = false; + thdHashFiles = null; + }); + + void HashFilesFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - lblProgress.Visible = false; - prgProgress.Visible = false; - lblProgress2.Visible = false; - prgProgress2.Visible = false; - Workers.Failed -= HashFilesFailed; - Workers.Finished -= HashFilesFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; - thdHashFiles = null; + lblProgress.Visible = false; + prgProgress.Visible = false; + lblProgress2.Visible = false; + prgProgress2.Visible = false; + Workers.Failed -= HashFilesFailed; + Workers.Finished -= HashFilesFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + thdHashFiles = null; - lblProgress.Visible = true; - prgProgress.Visible = true; + lblProgress.Visible = true; + prgProgress.Visible = true; - thdCheckFiles = new Thread(Workers.CheckDbForFiles); - Workers.Failed += ChkFilesFailed; - Workers.Finished += ChkFilesFinished; - Workers.UpdateProgress += UpdateProgress; - Workers.UpdateProgress2 += UpdateProgress2; - Workers.AddFileForApp += AddFile; - Workers.AddApp += AddApp; - thdCheckFiles.Start(); - }); - } + thdCheckFiles = new Thread(Workers.CheckDbForFiles); + Workers.Failed += ChkFilesFailed; + Workers.Finished += ChkFilesFinished; + Workers.UpdateProgress += UpdateProgress; + Workers.UpdateProgress2 += UpdateProgress2; + Workers.AddFileForApp += AddFile; + Workers.AddApp += AddApp; + thdCheckFiles.Start(); + }); - void ChkFilesFailed(string text) + void ChkFilesFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(!stopped) MessageBox.Show(text, MessageBoxType.Error); - prgProgress.Visible = false; - btnStop.Visible = false; - btnClose.Visible = false; - btnExit.Enabled = true; - Workers.Failed -= ChkFilesFailed; - Workers.Finished -= ChkFilesFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; - Workers.AddFileForApp -= AddFile; - Workers.AddApp -= AddApp; - thdCheckFiles?.Abort(); - thdHashFiles = null; - fileView?.Clear(); - if(appView == null) return; + if(!stopped) + MessageBox.Show(text, MessageBoxType.Error); - tabApps.Visible = false; - appView.Clear(); - }); - } + prgProgress.Visible = false; + btnStop.Visible = false; + btnClose.Visible = false; + btnExit.Enabled = true; + Workers.Failed -= ChkFilesFailed; + Workers.Finished -= ChkFilesFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + Workers.AddFileForApp -= AddFile; + Workers.AddApp -= AddApp; + thdCheckFiles?.Abort(); + thdHashFiles = null; + fileView?.Clear(); - void ChkFilesFinished() + if(appView == null) + return; + + tabApps.Visible = false; + appView.Clear(); + }); + + void ChkFilesFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + Workers.Failed -= ChkFilesFailed; + Workers.Finished -= ChkFilesFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + Workers.AddFileForApp -= AddFile; + Workers.AddApp -= AddApp; + + thdCheckFiles?.Abort(); + + thdHashFiles = null; + lblProgress.Visible = false; + prgProgress.Visible = false; + btnStop.Visible = false; + + if(Context.Executables?.Count > 0 || + Context.Readmes?.Count > 0) { - Workers.Failed -= ChkFilesFailed; - Workers.Finished -= ChkFilesFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; - Workers.AddFileForApp -= AddFile; - Workers.AddApp -= AddApp; + var importMetadataDlg = new dlgImportMetadata(); + importMetadataDlg.ShowModal(this); - thdCheckFiles?.Abort(); - - thdHashFiles = null; - lblProgress.Visible = false; - prgProgress.Visible = false; - btnStop.Visible = false; - - if(Context.Executables?.Count > 0 || Context.Readmes?.Count > 0) + if(!importMetadataDlg.canceled && + (importMetadataDlg.chosenArchitectures.Count > 0 || importMetadataDlg.chosenOses.Count > 0 || + !string.IsNullOrWhiteSpace(importMetadataDlg.description) || + !string.IsNullOrWhiteSpace(importMetadataDlg.developer) || + !string.IsNullOrWhiteSpace(importMetadataDlg.product) || + !string.IsNullOrWhiteSpace(importMetadataDlg.publisher) || + !string.IsNullOrWhiteSpace(importMetadataDlg.version))) { - dlgImportMetadata importMetadataDlg = new dlgImportMetadata(); - importMetadataDlg.ShowModal(this); + if(Context.Metadata == null && + (importMetadataDlg.chosenArchitectures.Count > 0 || importMetadataDlg.chosenOses.Count > 0 || + !string.IsNullOrWhiteSpace(importMetadataDlg.developer) || + !string.IsNullOrWhiteSpace(importMetadataDlg.product) || + !string.IsNullOrWhiteSpace(importMetadataDlg.publisher) || + !string.IsNullOrWhiteSpace(importMetadataDlg.version))) + Context.Metadata = new CICMMetadataType(); - if(!importMetadataDlg.canceled && (importMetadataDlg.chosenArchitectures.Count > 0 || - importMetadataDlg.chosenOses.Count > 0 || - !string.IsNullOrWhiteSpace(importMetadataDlg.description) || - !string.IsNullOrWhiteSpace(importMetadataDlg.developer) || - !string.IsNullOrWhiteSpace(importMetadataDlg.product) || - !string.IsNullOrWhiteSpace(importMetadataDlg.publisher) || - !string.IsNullOrWhiteSpace(importMetadataDlg.version))) - { - if(Context.Metadata == null && (importMetadataDlg.chosenArchitectures.Count > 0 || - importMetadataDlg.chosenOses.Count > 0 || - !string.IsNullOrWhiteSpace(importMetadataDlg.developer) || - !string.IsNullOrWhiteSpace(importMetadataDlg.product) || - !string.IsNullOrWhiteSpace(importMetadataDlg.publisher) || - !string.IsNullOrWhiteSpace(importMetadataDlg.version))) - Context.Metadata = new CICMMetadataType(); + if(!string.IsNullOrWhiteSpace(importMetadataDlg.description)) + txtDescription.Text = importMetadataDlg.description; - if(!string.IsNullOrWhiteSpace(importMetadataDlg.description)) - txtDescription.Text = importMetadataDlg.description; - if(!string.IsNullOrWhiteSpace(importMetadataDlg.product)) - Context.Metadata.Name = importMetadataDlg.product; - if(!string.IsNullOrWhiteSpace(importMetadataDlg.publisher)) - Context.Metadata.Publisher = new[] {importMetadataDlg.publisher}; - if(!string.IsNullOrWhiteSpace(importMetadataDlg.developer)) - Context.Metadata.Developer = new[] {importMetadataDlg.developer}; + if(!string.IsNullOrWhiteSpace(importMetadataDlg.product)) + Context.Metadata.Name = importMetadataDlg.product; - if(importMetadataDlg.chosenArchitectures.Count > 0) - Context.Metadata.Architectures = importMetadataDlg.chosenArchitectures.ToArray(); - - if(importMetadataDlg.chosenOses.Count > 0) + if(!string.IsNullOrWhiteSpace(importMetadataDlg.publisher)) + Context.Metadata.Publisher = new[] { - List reqOs = new List(); - foreach(TargetOsEntry osEntry in importMetadataDlg.chosenOses) - reqOs.Add(new RequiredOperatingSystemType - { - Name = osEntry.name, - Version = new[] {osEntry.version} - }); + importMetadataDlg.publisher + }; - Context.Metadata.RequiredOperatingSystems = reqOs.ToArray(); - } + if(!string.IsNullOrWhiteSpace(importMetadataDlg.developer)) + Context.Metadata.Developer = new[] + { + importMetadataDlg.developer + }; + + if(importMetadataDlg.chosenArchitectures.Count > 0) + Context.Metadata.Architectures = importMetadataDlg.chosenArchitectures.ToArray(); + + if(importMetadataDlg.chosenOses.Count > 0) + { + List reqOs = new List(); + + foreach(TargetOsEntry osEntry in importMetadataDlg.chosenOses) + reqOs.Add(new RequiredOperatingSystemType + { + Name = osEntry.name, + Version = new[] + { + osEntry.version + } + }); + + Context.Metadata.RequiredOperatingSystems = reqOs.ToArray(); } } + } - btnClose.Visible = true; - btnExit.Enabled = true; - btnPack.Visible = true; - btnPack.Enabled = true; - btnRemoveFile.Visible = true; - btnToggleCrack.Visible = true; - btnRemoveFile.Enabled = true; - btnToggleCrack.Enabled = true; + btnClose.Visible = true; + btnExit.Enabled = true; + btnPack.Visible = true; + btnPack.Enabled = true; + btnRemoveFile.Visible = true; + btnToggleCrack.Visible = true; + btnRemoveFile.Enabled = true; + btnToggleCrack.Enabled = true; - txtFormat.ReadOnly = false; - txtDescription.ReadOnly = false; - chkOem.Enabled = true; - chkFiles.Enabled = true; - chkUpdate.Enabled = true; - chkUpgrade.Enabled = true; - chkInstaller.Enabled = true; - chkSource.Enabled = true; + txtFormat.ReadOnly = false; + txtDescription.ReadOnly = false; + chkOem.Enabled = true; + chkFiles.Enabled = true; + chkUpdate.Enabled = true; + chkUpgrade.Enabled = true; + chkInstaller.Enabled = true; + chkSource.Enabled = true; - btnMetadata.Visible = true; - if(Context.Metadata != null) - { - if(Context.Metadata.Developer != null) - foreach(string developer in Context.Metadata.Developer) - { - if(!string.IsNullOrWhiteSpace(txtDeveloper.Text)) txtDeveloper.Text += ","; - txtDeveloper.Text += developer; - } + btnMetadata.Visible = true; - if(!string.IsNullOrWhiteSpace(Context.Metadata.Name)) txtProduct.Text = Context.Metadata.Name; - if(!string.IsNullOrWhiteSpace(Context.Metadata.Version)) txtVersion.Text = Context.Metadata.Version; - - if(Context.Metadata.Languages != null) - foreach(LanguagesTypeLanguage language in Context.Metadata.Languages) - { - if(!string.IsNullOrWhiteSpace(txtLanguages.Text)) txtLanguages.Text += ","; - txtLanguages.Text += language; - } - - if(Context.Metadata.Architectures != null) - foreach(ArchitecturesTypeArchitecture architecture in Context.Metadata.Architectures) - { - if(!string.IsNullOrWhiteSpace(txtArchitecture.Text)) txtArchitecture.Text += ","; - txtArchitecture.Text += architecture; - } - - if(Context.Metadata.RequiredOperatingSystems != null) - foreach(string targetos in Context - .Metadata.RequiredOperatingSystems.Select(os => os.Name).Distinct()) - { - if(!string.IsNullOrWhiteSpace(txtTargetOs.Text)) txtTargetOs.Text += ","; - txtTargetOs.Text += targetos; - } - - btnMetadata.BackgroundColor = Colors.Green; - } - else btnMetadata.BackgroundColor = Colors.Red; - - lblStatus.Visible = true; - lblStatus.Text = $"{fileView.Count} files ({knownFiles} already known)"; - }); - } - - void AddFile(string filename, string hash, bool known, bool isCrack) - { - Application.Instance.Invoke(delegate + if(Context.Metadata != null) { - fileView.Add(new FileEntry {Path = filename, Hash = hash, Known = known, IsCrack = isCrack}); - btnPack.Enabled |= !known; - if(known) knownFiles++; - }); - } + if(Context.Metadata.Developer != null) + foreach(string developer in Context.Metadata.Developer) + { + if(!string.IsNullOrWhiteSpace(txtDeveloper.Text)) + txtDeveloper.Text += ","; - void AddApp(DbEntry app) + txtDeveloper.Text += developer; + } + + if(!string.IsNullOrWhiteSpace(Context.Metadata.Name)) + txtProduct.Text = Context.Metadata.Name; + + if(!string.IsNullOrWhiteSpace(Context.Metadata.Version)) + txtVersion.Text = Context.Metadata.Version; + + if(Context.Metadata.Languages != null) + foreach(LanguagesTypeLanguage language in Context.Metadata.Languages) + { + if(!string.IsNullOrWhiteSpace(txtLanguages.Text)) + txtLanguages.Text += ","; + + txtLanguages.Text += language; + } + + if(Context.Metadata.Architectures != null) + foreach(ArchitecturesTypeArchitecture architecture in Context.Metadata.Architectures) + { + if(!string.IsNullOrWhiteSpace(txtArchitecture.Text)) + txtArchitecture.Text += ","; + + txtArchitecture.Text += architecture; + } + + if(Context.Metadata.RequiredOperatingSystems != null) + foreach(string targetos in Context.Metadata.RequiredOperatingSystems.Select(os => os.Name). + Distinct()) + { + if(!string.IsNullOrWhiteSpace(txtTargetOs.Text)) + txtTargetOs.Text += ","; + + txtTargetOs.Text += targetos; + } + + btnMetadata.BackgroundColor = Colors.Green; + } + else + btnMetadata.BackgroundColor = Colors.Red; + + lblStatus.Visible = true; + lblStatus.Text = $"{fileView.Count} files ({knownFiles} already known)"; + }); + + void AddFile(string filename, string hash, bool known, bool isCrack) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + fileView.Add(new FileEntry { - tabApps.Visible = true; - appView.Add(new DBEntryForEto(app)); + Path = filename, + Hash = hash, + Known = known, + IsCrack = isCrack }); - } + + btnPack.Enabled |= !known; + + if(known) + knownFiles++; + }); + + void AddApp(DbEntry app) => Application.Instance.Invoke(delegate + { + tabApps.Visible = true; + appView.Add(new DBEntryForEto(app)); + }); protected void OnBtnExitClicked(object sender, EventArgs e) { - if(btnClose.Enabled) OnBtnCloseClicked(sender, e); + if(btnClose.Enabled) + OnBtnCloseClicked(sender, e); Close(); } @@ -527,6 +639,7 @@ namespace apprepodbmgr.Eto btnRemoveFile.Visible = false; btnToggleCrack.Visible = false; fileView?.Clear(); + if(appView != null) { tabApps.Visible = false; @@ -574,17 +687,22 @@ namespace apprepodbmgr.Eto lblStatus.Visible = false; } - void UpdateProgress(string text, string inner, long current, long maximum) - { + void UpdateProgress(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { - if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) - lblProgress.Text = $"{text}: {inner}"; - else if(!string.IsNullOrWhiteSpace(inner)) lblProgress.Text = inner; - else lblProgress.Text = text; + if(!string.IsNullOrWhiteSpace(text) && + !string.IsNullOrWhiteSpace(inner)) + lblProgress.Text = $"{text}: {inner}"; + else if(!string.IsNullOrWhiteSpace(inner)) + lblProgress.Text = inner; + else + lblProgress.Text = text; + if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -596,21 +714,26 @@ namespace apprepodbmgr.Eto prgProgress.MaxValue = (int)maximum; prgProgress.Value = (int)current; } - else prgProgress.Indeterminate = true; + else + prgProgress.Indeterminate = true; }); - } - void UpdateProgress2(string text, string inner, long current, long maximum) - { + void UpdateProgress2(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { - if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) - lblProgress2.Text = $"{text}: {inner}"; - else if(!string.IsNullOrWhiteSpace(inner)) lblProgress2.Text = inner; - else lblProgress2.Text = text; + if(!string.IsNullOrWhiteSpace(text) && + !string.IsNullOrWhiteSpace(inner)) + lblProgress2.Text = $"{text}: {inner}"; + else if(!string.IsNullOrWhiteSpace(inner)) + lblProgress2.Text = inner; + else + lblProgress2.Text = text; + if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -622,9 +745,9 @@ namespace apprepodbmgr.Eto prgProgress2.MaxValue = (int)maximum; prgProgress2.Value = (int)current; } - else prgProgress2.Indeterminate = true; + else + prgProgress2.Indeterminate = true; }); - } protected void OnBtnStopClicked(object sender, EventArgs e) { @@ -703,7 +826,8 @@ namespace apprepodbmgr.Eto thdRemoveTemp = new Thread(Workers.RemoveTempFolder); thdRemoveTemp.Start(); } - else RestoreUi(); + else + RestoreUi(); } void RestoreUi() @@ -740,36 +864,32 @@ namespace apprepodbmgr.Eto Workers.UpdateProgress2 -= UpdateProgress2; btnStop.Visible = false; fileView?.Clear(); - if(appView == null) return; + + if(appView == null) + return; tabApps.Visible = false; appView.Clear(); } - void RemoveTempFilesFailed(string text) + void RemoveTempFilesFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - MessageBox.Show(text, MessageBoxType.Error); - Workers.Failed -= RemoveTempFilesFailed; - Workers.Finished -= RemoveTempFilesFinished; - Context.Path = null; - Context.TmpFolder = null; - RestoreUi(); - }); - } + MessageBox.Show(text, MessageBoxType.Error); + Workers.Failed -= RemoveTempFilesFailed; + Workers.Finished -= RemoveTempFilesFinished; + Context.Path = null; + Context.TmpFolder = null; + RestoreUi(); + }); - void RemoveTempFilesFinished() + void RemoveTempFilesFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - Workers.Failed -= RemoveTempFilesFailed; - Workers.Finished -= RemoveTempFilesFinished; - Context.Path = null; - Context.TmpFolder = null; - RestoreUi(); - }); - } + Workers.Failed -= RemoveTempFilesFailed; + Workers.Finished -= RemoveTempFilesFinished; + Context.Path = null; + Context.TmpFolder = null; + RestoreUi(); + }); void AddToDatabase() { @@ -808,13 +928,13 @@ namespace apprepodbmgr.Eto if(Context.Metadata != null) { - MemoryStream ms = new MemoryStream(); - XmlSerializer xs = new XmlSerializer(typeof(CICMMetadataType)); + var ms = new MemoryStream(); + var xs = new XmlSerializer(typeof(CICMMetadataType)); xs.Serialize(ms, Context.Metadata); Context.DbInfo.Xml = ms.ToArray(); - JsonSerializer js = new JsonSerializer(); + var js = new JsonSerializer(); ms = new MemoryStream(); - StreamWriter sw = new StreamWriter(ms); + var sw = new StreamWriter(ms); js.Serialize(sw, Context.Metadata, typeof(CICMMetadataType)); Context.DbInfo.Json = ms.ToArray(); } @@ -828,50 +948,53 @@ namespace apprepodbmgr.Eto thdAddFiles.Start(); } - void AddFilesToDbFinished() + void AddFilesToDbFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + Workers.UpdateProgress -= UpdateProgress; + Workers.Finished -= AddFilesToDbFinished; + Workers.Failed -= AddFilesToDbFailed; + + thdAddFiles?.Abort(); + + long counter = 0; + fileView.Clear(); + + foreach(KeyValuePair kvp in Context.Hashes) { - Workers.UpdateProgress -= UpdateProgress; - Workers.Finished -= AddFilesToDbFinished; - Workers.Failed -= AddFilesToDbFailed; + UpdateProgress(null, "Updating table", counter, Context.Hashes.Count); - thdAddFiles?.Abort(); - - long counter = 0; - fileView.Clear(); - foreach(KeyValuePair kvp in Context.Hashes) + fileView.Add(new FileEntry { - UpdateProgress(null, "Updating table", counter, Context.Hashes.Count); - fileView.Add(new FileEntry {Path = kvp.Key, Hash = kvp.Value.Sha256, Known = true}); - counter++; - } + Path = kvp.Key, + Hash = kvp.Value.Sha256, + Known = true + }); - // TODO: Update application table + counter++; + } - OnAddedApp?.Invoke(Context.DbInfo); + // TODO: Update application table - lblProgress.Visible = false; - prgProgress.Visible = false; - btnClose.Enabled = true; - }); - } + OnAddedApp?.Invoke(Context.DbInfo); - void AddFilesToDbFailed(string text) + lblProgress.Visible = false; + prgProgress.Visible = false; + btnClose.Enabled = true; + }); + + void AddFilesToDbFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(!stopped) MessageBox.Show(text, MessageBoxType.Error); + if(!stopped) + MessageBox.Show(text, MessageBoxType.Error); - Workers.UpdateProgress -= UpdateProgress; - Workers.Finished -= AddFilesToDbFinished; - Workers.Failed -= AddFilesToDbFailed; + Workers.UpdateProgress -= UpdateProgress; + Workers.Finished -= AddFilesToDbFinished; + Workers.Failed -= AddFilesToDbFailed; - thdAddFiles?.Abort(); + thdAddFiles?.Abort(); - ChkFilesFinished(); - }); - } + ChkFilesFinished(); + }); protected void OnBtnPackClicked(object sender, EventArgs e) { @@ -916,68 +1039,69 @@ namespace apprepodbmgr.Eto thdPackFiles.Start(); } - void PackFilesFinished(string text) + void PackFilesFinished(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; - Workers.FinishedWithText -= PackFilesFinished; - Workers.Failed -= PackFilesFailed; - prgProgress2.Visible = false; - lblProgress2.Visible = false; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + Workers.FinishedWithText -= PackFilesFinished; + Workers.Failed -= PackFilesFailed; + prgProgress2.Visible = false; + lblProgress2.Visible = false; - thdPackFiles?.Abort(); + thdPackFiles?.Abort(); - AddToDatabase(); + AddToDatabase(); - MessageBox.Show(text); - }); - } + MessageBox.Show(text); + }); - void PackFilesFailed(string text) + void PackFilesFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(!stopped) MessageBox.Show(text, MessageBoxType.Error); + if(!stopped) + MessageBox.Show(text, MessageBoxType.Error); - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; - Workers.FinishedWithText -= PackFilesFinished; - Workers.Failed -= PackFilesFailed; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + Workers.FinishedWithText -= PackFilesFinished; + Workers.Failed -= PackFilesFailed; - thdPackFiles?.Abort(); + thdPackFiles?.Abort(); - btnRemoveFile.Enabled = true; - btnToggleCrack.Enabled = true; - btnPack.Enabled = true; - btnClose.Enabled = true; - prgProgress.Visible = false; - prgProgress2.Visible = false; - lblProgress.Visible = false; - lblProgress2.Visible = false; - txtFormat.ReadOnly = false; - txtDescription.ReadOnly = false; - chkOem.Enabled = true; - chkFiles.Enabled = true; - chkUpdate.Enabled = true; - chkUpgrade.Enabled = true; - chkInstaller.Enabled = true; - chkSource.Enabled = true; - }); - } + btnRemoveFile.Enabled = true; + btnToggleCrack.Enabled = true; + btnPack.Enabled = true; + btnClose.Enabled = true; + prgProgress.Visible = false; + prgProgress2.Visible = false; + lblProgress.Visible = false; + lblProgress2.Visible = false; + txtFormat.ReadOnly = false; + txtDescription.ReadOnly = false; + chkOem.Enabled = true; + chkFiles.Enabled = true; + chkUpdate.Enabled = true; + chkUpgrade.Enabled = true; + chkInstaller.Enabled = true; + chkSource.Enabled = true; + }); protected void OnBtnArchiveClicked(object sender, EventArgs e) { if(!Context.UnarUsable) { MessageBox.Show("Cannot open archives without a working unar installation.", MessageBoxType.Error); + return; } - OpenFileDialog dlgFile = new OpenFileDialog {Title = "Open archive", MultiSelect = false}; + var dlgFile = new OpenFileDialog + { + Title = "Open archive", + MultiSelect = false + }; - if(dlgFile.ShowDialog(this) != DialogResult.Ok) return; + if(dlgFile.ShowDialog(this) != DialogResult.Ok) + return; knownFiles = 0; stopped = false; @@ -997,110 +1121,109 @@ namespace apprepodbmgr.Eto thdOpenArchive.Start(); } - void OpenArchiveFailed(string text) + void OpenArchiveFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(!stopped) MessageBox.Show(text, MessageBoxType.Error); - lblProgress.Visible = false; - prgProgress.Visible = false; - btnExit.Enabled = true; - btnFolder.Visible = true; - btnArchive.Visible = true; - btnStop.Visible = false; - Workers.Failed -= OpenArchiveFailed; - Workers.Finished -= OpenArchiveFinished; - thdOpenArchive = null; - }); - } + if(!stopped) + MessageBox.Show(text, MessageBoxType.Error); - void OpenArchiveFinished() + lblProgress.Visible = false; + prgProgress.Visible = false; + btnExit.Enabled = true; + btnFolder.Visible = true; + btnArchive.Visible = true; + btnStop.Visible = false; + Workers.Failed -= OpenArchiveFailed; + Workers.Finished -= OpenArchiveFinished; + thdOpenArchive = null; + }); + + void OpenArchiveFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - stopped = false; - lblProgress.Text = "Extracting archive"; - prgProgress.Visible = true; - prgProgress2.Visible = true; - btnExit.Enabled = false; - btnFolder.Visible = false; - btnArchive.Visible = false; - Workers.UpdateProgress += UpdateProgress; - lblProgress.Visible = true; - lblProgress2.Visible = true; - Workers.Failed -= OpenArchiveFailed; - Workers.Finished -= OpenArchiveFinished; - thdOpenArchive = null; - Workers.Failed += ExtractArchiveFailed; - Workers.Finished += ExtractArchiveFinished; - Workers.UpdateProgress2 += UpdateProgress2; - thdExtractArchive = new Thread(Workers.ExtractArchive); - thdExtractArchive.Start(); - }); - } + stopped = false; + lblProgress.Text = "Extracting archive"; + prgProgress.Visible = true; + prgProgress2.Visible = true; + btnExit.Enabled = false; + btnFolder.Visible = false; + btnArchive.Visible = false; + Workers.UpdateProgress += UpdateProgress; + lblProgress.Visible = true; + lblProgress2.Visible = true; + Workers.Failed -= OpenArchiveFailed; + Workers.Finished -= OpenArchiveFinished; + thdOpenArchive = null; + Workers.Failed += ExtractArchiveFailed; + Workers.Finished += ExtractArchiveFinished; + Workers.UpdateProgress2 += UpdateProgress2; + thdExtractArchive = new Thread(Workers.ExtractArchive); + thdExtractArchive.Start(); + }); - void ExtractArchiveFailed(string text) + void ExtractArchiveFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(!stopped) MessageBox.Show(text, MessageBoxType.Error); - lblProgress2.Visible = false; - prgProgress2.Visible = false; - btnExit.Enabled = true; - btnFolder.Visible = true; - btnArchive.Visible = true; - Workers.Failed -= ExtractArchiveFailed; - Workers.Finished -= ExtractArchiveFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; - thdExtractArchive = null; - if(Context.TmpFolder == null) return; + if(!stopped) + MessageBox.Show(text, MessageBoxType.Error); - btnStop.Visible = false; - lblProgress.Text = "Removing temporary files"; - prgProgress.Indeterminate = true; - Workers.Failed += RemoveTempFilesFailed; - Workers.Finished += RemoveTempFilesFinished; - thdRemoveTemp = new Thread(Workers.RemoveTempFolder); - thdRemoveTemp.Start(); - }); - } + lblProgress2.Visible = false; + prgProgress2.Visible = false; + btnExit.Enabled = true; + btnFolder.Visible = true; + btnArchive.Visible = true; + Workers.Failed -= ExtractArchiveFailed; + Workers.Finished -= ExtractArchiveFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + thdExtractArchive = null; - void ExtractArchiveFinished() + if(Context.TmpFolder == null) + return; + + btnStop.Visible = false; + lblProgress.Text = "Removing temporary files"; + prgProgress.Indeterminate = true; + Workers.Failed += RemoveTempFilesFailed; + Workers.Finished += RemoveTempFilesFinished; + thdRemoveTemp = new Thread(Workers.RemoveTempFolder); + thdRemoveTemp.Start(); + }); + + void ExtractArchiveFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - stopped = false; - lblProgress.Text = "Finding files"; - lblProgress.Visible = true; - lblProgress2.Visible = false; - prgProgress.Visible = true; - btnExit.Enabled = false; - btnFolder.Visible = false; - btnArchive.Visible = false; - Workers.Failed -= ExtractArchiveFailed; - Workers.Finished -= ExtractArchiveFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; - prgProgress.Indeterminate = true; + stopped = false; + lblProgress.Text = "Finding files"; + lblProgress.Visible = true; + lblProgress2.Visible = false; + prgProgress.Visible = true; + btnExit.Enabled = false; + btnFolder.Visible = false; + btnArchive.Visible = false; + Workers.Failed -= ExtractArchiveFailed; + Workers.Finished -= ExtractArchiveFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + prgProgress.Indeterminate = true; - thdExtractArchive = null; - thdFindFiles = new Thread(Workers.FindFiles); - Workers.Failed += FindFilesFailed; - Workers.Finished += FindFilesFinished; - btnStop.Visible = true; - thdFindFiles.Start(); - }); - } + thdExtractArchive = null; + thdFindFiles = new Thread(Workers.FindFiles); + Workers.Failed += FindFilesFailed; + Workers.Finished += FindFilesFinished; + btnStop.Visible = true; + thdFindFiles.Start(); + }); protected void OnBtnMetadataClicked(object sender, EventArgs e) { - dlgMetadata _dlgMetadata = new dlgMetadata {Metadata = Context.Metadata}; + var _dlgMetadata = new dlgMetadata + { + Metadata = Context.Metadata + }; + _dlgMetadata.FillFields(); _dlgMetadata.ShowModal(this); - if(!_dlgMetadata.Modified) return; + if(!_dlgMetadata.Modified) + return; Context.Metadata = _dlgMetadata.Metadata; @@ -1108,7 +1231,9 @@ namespace apprepodbmgr.Eto if(Context.Metadata.Developer != null) foreach(string developer in Context.Metadata.Developer) { - if(!string.IsNullOrWhiteSpace(txtDeveloper.Text)) txtDeveloper.Text += ","; + if(!string.IsNullOrWhiteSpace(txtDeveloper.Text)) + txtDeveloper.Text += ","; + txtDeveloper.Text += developer; } @@ -1124,7 +1249,9 @@ namespace apprepodbmgr.Eto if(Context.Metadata.Languages != null) foreach(LanguagesTypeLanguage language in Context.Metadata.Languages) { - if(!string.IsNullOrWhiteSpace(txtLanguages.Text)) txtLanguages.Text += ","; + if(!string.IsNullOrWhiteSpace(txtLanguages.Text)) + txtLanguages.Text += ","; + txtLanguages.Text += language; } @@ -1132,16 +1259,20 @@ namespace apprepodbmgr.Eto if(Context.Metadata.Architectures != null) foreach(ArchitecturesTypeArchitecture architecture in Context.Metadata.Architectures) { - if(!string.IsNullOrWhiteSpace(txtArchitecture.Text)) txtArchitecture.Text += ","; + if(!string.IsNullOrWhiteSpace(txtArchitecture.Text)) + txtArchitecture.Text += ","; + txtArchitecture.Text += architecture; } if(string.IsNullOrWhiteSpace(txtTargetOs.Text)) if(Context.Metadata.RequiredOperatingSystems != null) - foreach(string targetos in Context.Metadata.RequiredOperatingSystems.Select(os => os.Name) - .Distinct()) + foreach(string targetos in Context.Metadata.RequiredOperatingSystems.Select(os => os.Name). + Distinct()) { - if(!string.IsNullOrWhiteSpace(txtTargetOs.Text)) txtTargetOs.Text += ","; + if(!string.IsNullOrWhiteSpace(txtTargetOs.Text)) + txtTargetOs.Text += ","; + txtTargetOs.Text += targetos; } @@ -1150,14 +1281,17 @@ namespace apprepodbmgr.Eto protected void OnBtnRemoveFileClicked(object sender, EventArgs e) { - if(treeFiles.SelectedItem == null) return; + if(treeFiles.SelectedItem == null) + return; string name = ((FileEntry)treeFiles.SelectedItem).Path; string filesPath; - if(!string.IsNullOrEmpty(Context.TmpFolder) && Directory.Exists(Context.TmpFolder)) - filesPath = Context.TmpFolder; - else filesPath = Context.Path; + if(!string.IsNullOrEmpty(Context.TmpFolder) && + Directory.Exists(Context.TmpFolder)) + filesPath = Context.TmpFolder; + else + filesPath = Context.Path; Context.Hashes.Remove(name); Context.Files.Remove(Path.Combine(filesPath, name)); @@ -1166,24 +1300,34 @@ namespace apprepodbmgr.Eto protected void OnBtnToggleCrackClicked(object sender, EventArgs e) { - if(treeFiles.SelectedItem == null) return; + if(treeFiles.SelectedItem == null) + return; string name = ((FileEntry)treeFiles.SelectedItem).Path; bool known = ((FileEntry)treeFiles.SelectedItem).Known; - if(!Context.Hashes.TryGetValue(name, out DbAppFile appFile)) return; + if(!Context.Hashes.TryGetValue(name, out DbAppFile appFile)) + return; appFile.Crack = !appFile.Crack; Context.Hashes.Remove(name); Context.Hashes.Add(name, appFile); ((FileEntry)treeFiles.SelectedItem).IsCrack = appFile.Crack; fileView.Remove((FileEntry)treeFiles.SelectedItem); - fileView.Add(new FileEntry {Path = name, Hash = appFile.Sha256, Known = known, IsCrack = appFile.Crack}); + + fileView.Add(new FileEntry + { + Path = name, + Hash = appFile.Sha256, + Known = known, + IsCrack = appFile.Crack + }); } void treeFilesSelectionChanged(object sender, EventArgs e) { - if(treeFiles.SelectedItem == null) return; + if(treeFiles.SelectedItem == null) + return; btnToggleCrack.Text = ((FileEntry)treeFiles.SelectedItem).IsCrack ? "Mark as not crack" : "Mark as crack"; } diff --git a/apprepodbmgr.Eto/dlgBlockMedia.xeto.cs b/apprepodbmgr.Eto/dlgBlockMedia.xeto.cs index cb5b7be..dd68d9d 100644 --- a/apprepodbmgr.Eto/dlgBlockMedia.xeto.cs +++ b/apprepodbmgr.Eto/dlgBlockMedia.xeto.cs @@ -44,29 +44,29 @@ namespace apprepodbmgr.Eto DumpHardwareType dumpHwIter; bool editingDumpHw; - bool editingPartition; - FileSystemType filesystemIter; - ObservableCollection lstAdditionalInformation; + bool editingPartition; + FileSystemType filesystemIter; + readonly ObservableCollection lstAdditionalInformation; - ObservableCollection lstAta; - ObservableCollection lstCID; - ObservableCollection lstCSD; - ObservableCollection lstDumpHw; - ObservableCollection lstECSD; - ObservableCollection lstEVPDs; - ObservableCollection lstInquiry; - ObservableCollection lstLogSense; - ObservableCollection lstMAM; - ObservableCollection lstModeSense; - ObservableCollection lstModeSense10; - ObservableCollection lstPartitions; - ObservableCollection lstPCIConfiguration; - ObservableCollection lstPCIOptionROM; - ObservableCollection lstPCMCIACIS; - ObservableCollection lstTracks; - ObservableCollection lstUSBDescriptors; - public BlockMediaType Metadata; - public bool Modified; + readonly ObservableCollection lstAta; + readonly ObservableCollection lstCID; + readonly ObservableCollection lstCSD; + ObservableCollection lstDumpHw; + readonly ObservableCollection lstECSD; + ObservableCollection lstEVPDs; + readonly ObservableCollection lstInquiry; + readonly ObservableCollection lstLogSense; + readonly ObservableCollection lstMAM; + readonly ObservableCollection lstModeSense; + readonly ObservableCollection lstModeSense10; + ObservableCollection lstPartitions; + readonly ObservableCollection lstPCIConfiguration; + readonly ObservableCollection lstPCIOptionROM; + readonly ObservableCollection lstPCMCIACIS; + ObservableCollection lstTracks; + readonly ObservableCollection lstUSBDescriptors; + public BlockMediaType Metadata; + public bool Modified; PartitionType partitionIter; ScansType scans; @@ -90,6 +90,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Sequence" }); + treePartitions.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -98,6 +99,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Start" }); + treePartitions.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -106,19 +108,31 @@ namespace apprepodbmgr.Eto }, HeaderText = "End" }); + treePartitions.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Type)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Type) + }, HeaderText = "Type" }); + treePartitions.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Name)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Name) + }, HeaderText = "Name" }); + treePartitions.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Description)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Description) + }, HeaderText = "Description" }); @@ -130,12 +144,19 @@ namespace apprepodbmgr.Eto #region Set filesystems table treeFilesystems.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Type)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Type) + }, HeaderText = "Type" }); + treeFilesystems.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.VolumeName)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.VolumeName) + }, HeaderText = "Name" }); @@ -147,30 +168,49 @@ namespace apprepodbmgr.Eto treeDumpHardware.Columns.Add(new GridColumn { - DataCell = - new TextBoxCell {Binding = Binding.Property(r => r.Manufacturer)}, - HeaderText = "Manufacturer" + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Manufacturer) + }, + HeaderText = "Manufacturer" }); + treeDumpHardware.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Model)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Model) + }, HeaderText = "Model" }); + treeDumpHardware.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Revision)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Revision) + }, HeaderText = "Revision" }); + treeDumpHardware.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Firmware)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Firmware) + }, HeaderText = "Firmware" }); + treeDumpHardware.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Serial)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Serial) + }, HeaderText = "Serial" }); + treeDumpHardware.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -179,6 +219,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Software" }); + treeDumpHardware.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -187,12 +228,13 @@ namespace apprepodbmgr.Eto }, HeaderText = "Version" }); + treeDumpHardware.Columns.Add(new GridColumn { DataCell = new TextBoxCell { - Binding = Binding.Property(r => r.Software) - .Convert(v => v?.OperatingSystem) + Binding = Binding.Property(r => r.Software). + Convert(v => v?.OperatingSystem) }, HeaderText = "Operating system" }); @@ -209,6 +251,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Start" }); + treeExtents.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -221,11 +264,16 @@ namespace apprepodbmgr.Eto #region Set ATA IDENTIFY table lstAta = new ObservableCollection(); + treeATA.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeATA.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -234,16 +282,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeATA.DataStore = lstAta; #endregion Set ATA IDENTIFY table #region Set PCI configuration table lstPCIConfiguration = new ObservableCollection(); + treeConfiguration.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeConfiguration.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -252,16 +306,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeConfiguration.DataStore = lstPCIConfiguration; #endregion Set PCI configuration table #region Set PCMCIA CIS table lstPCMCIACIS = new ObservableCollection(); + treeCIS.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeCIS.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -270,16 +330,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeCIS.DataStore = lstPCMCIACIS; #endregion Set PCI option ROM table #region Set CID table lstCID = new ObservableCollection(); + treeCID.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeCID.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -288,16 +354,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeCID.DataStore = lstCID; #endregion Set CID table #region Set CSD table lstCSD = new ObservableCollection(); + treeCSD.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeCSD.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -306,16 +378,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeCSD.DataStore = lstCSD; #endregion Set CSD table #region Set Extended CSD table lstECSD = new ObservableCollection(); + treeECSD.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeECSD.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -324,16 +402,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeECSD.DataStore = lstECSD; #endregion Set Extended CSD table #region Set SCSI INQUIRY table lstInquiry = new ObservableCollection(); + treeInquiry.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeInquiry.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -342,16 +426,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeInquiry.DataStore = lstInquiry; #endregion Set SCSI INQUIRY table #region Set SCSI MODE SENSE table lstModeSense = new ObservableCollection(); + treeModeSense.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeModeSense.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -360,16 +450,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeModeSense.DataStore = lstModeSense; #endregion Set SCSI MODE SENSE table #region Set SCSI MODE SENSE (10) table lstModeSense10 = new ObservableCollection(); + treeModeSense10.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeModeSense10.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -378,16 +474,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeModeSense10.DataStore = lstModeSense10; #endregion Set SCSI MODE SENSE (10) table #region Set SCSI LOG SENSE table lstLogSense = new ObservableCollection(); + treeLogSense.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeLogSense.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -396,6 +498,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeLogSense.DataStore = lstLogSense; #endregion Set SCSI MODE SENSE (10) table @@ -410,11 +513,16 @@ namespace apprepodbmgr.Eto }, HeaderText = "Page" }); + treeEVPDs.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeEVPDs.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -431,11 +539,16 @@ namespace apprepodbmgr.Eto #region Set USB descriptors table lstUSBDescriptors = new ObservableCollection(); + treeDescriptors.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeDescriptors.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -444,16 +557,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeDescriptors.DataStore = lstUSBDescriptors; #endregion Set USB descriptors table #region Set MAM table lstMAM = new ObservableCollection(); + treeMAM.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeMAM.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -462,6 +581,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeMAM.DataStore = lstMAM; #endregion Set MAM table @@ -470,9 +590,13 @@ namespace apprepodbmgr.Eto treeOptionROM.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image.Value)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image.Value) + }, HeaderText = "File" }); + treeOptionROM.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -481,6 +605,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Offset" }); + treeOptionROM.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -500,9 +625,13 @@ namespace apprepodbmgr.Eto treeTracks.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image.Value)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image.Value) + }, HeaderText = "File" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -511,6 +640,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Offset" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -519,11 +649,16 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeTracks.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image.format)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image.format) + }, HeaderText = "Image format" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -532,6 +667,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Head" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -540,6 +676,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Cylinder" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -548,6 +685,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Start" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -556,6 +694,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "End" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -564,6 +703,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Sectors" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -572,9 +712,13 @@ namespace apprepodbmgr.Eto }, HeaderText = "Bytes per sector" }); + treeTracks.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Format)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Format) + }, HeaderText = "Track format" }); @@ -584,11 +728,16 @@ namespace apprepodbmgr.Eto #endregion Set tracks table lstAdditionalInformation = new ObservableCollection(); + treeAdditionalInformation.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.str)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.str) + }, HeaderText = "Information" }); + treeAdditionalInformation.DataStore = lstAdditionalInformation; treeAdditionalInformation.AllowMultipleSelection = false; @@ -627,45 +776,65 @@ namespace apprepodbmgr.Eto public void FillFields() { - if(Metadata == null) return; + if(Metadata == null) + return; + + txtImage.Text = Metadata.Image.Value; + txtFormat.Text = Metadata.Image.format; + + if(Metadata.Image.offsetSpecified) + txtOffset.Text = Metadata.Image.offset.ToString(); + + txtSize.Text = Metadata.Size.ToString(); + checksums = Metadata.Checksums; + contentChks = Metadata.ContentChecksums; - txtImage.Text = Metadata.Image.Value; - txtFormat.Text = Metadata.Image.format; - if(Metadata.Image.offsetSpecified) txtOffset.Text = Metadata.Image.offset.ToString(); - txtSize.Text = Metadata.Size.ToString(); - checksums = Metadata.Checksums; - contentChks = Metadata.ContentChecksums; if(Metadata.Sequence != null) { - lblMediaTitle.Visible = true; - txtMediaTitle.Visible = true; - lblSequence.Visible = true; - spSequence.Visible = true; - lblTotalMedia.Visible = true; - spTotalMedia.Visible = true; - lblSide.Visible = true; - spSide.Visible = true; - lblLayer.Visible = true; - spLayer.Visible = true; - chkSequence.Checked = true; - txtMediaTitle.Text = Metadata.Sequence.MediaTitle; - spSequence.Value = Metadata.Sequence.MediaSequence; - spTotalMedia.Value = Metadata.Sequence.TotalMedia; - if(Metadata.Sequence.SideSpecified) spSide.Value = Metadata.Sequence.Side; - if(Metadata.Sequence.LayerSpecified) spLayer.Value = Metadata.Sequence.Layer; + lblMediaTitle.Visible = true; + txtMediaTitle.Visible = true; + lblSequence.Visible = true; + spSequence.Visible = true; + lblTotalMedia.Visible = true; + spTotalMedia.Visible = true; + lblSide.Visible = true; + spSide.Visible = true; + lblLayer.Visible = true; + spLayer.Visible = true; + chkSequence.Checked = true; + txtMediaTitle.Text = Metadata.Sequence.MediaTitle; + spSequence.Value = Metadata.Sequence.MediaSequence; + spTotalMedia.Value = Metadata.Sequence.TotalMedia; + + if(Metadata.Sequence.SideSpecified) + spSide.Value = Metadata.Sequence.Side; + + if(Metadata.Sequence.LayerSpecified) + spLayer.Value = Metadata.Sequence.Layer; } - if(Metadata.Manufacturer != null) txtManufacturer.Text = Metadata.Manufacturer; - if(Metadata.Model != null) txtModel.Text = Metadata.Model; - if(Metadata.Serial != null) txtSerial.Text = Metadata.Serial; - if(Metadata.Firmware != null) txtFirmware.Text = Metadata.Firmware; - if(Metadata.Interface != null) txtInterface.Text = Metadata.Interface; - spPhysicalBlockSize.Value = Metadata.PhysicalBlockSize; - spLogicalBlockSize.Value = Metadata.LogicalBlockSize; - txtBlocks.Text = Metadata.LogicalBlocks.ToString(); - variableBlockSize = Metadata.VariableBlockSize; - tapeInformation = Metadata.TapeInformation; - scans = Metadata.Scans; + if(Metadata.Manufacturer != null) + txtManufacturer.Text = Metadata.Manufacturer; + + if(Metadata.Model != null) + txtModel.Text = Metadata.Model; + + if(Metadata.Serial != null) + txtSerial.Text = Metadata.Serial; + + if(Metadata.Firmware != null) + txtFirmware.Text = Metadata.Firmware; + + if(Metadata.Interface != null) + txtInterface.Text = Metadata.Interface; + + spPhysicalBlockSize.Value = Metadata.PhysicalBlockSize; + spLogicalBlockSize.Value = Metadata.LogicalBlockSize; + txtBlocks.Text = Metadata.LogicalBlocks.ToString(); + variableBlockSize = Metadata.VariableBlockSize; + tapeInformation = Metadata.TapeInformation; + scans = Metadata.Scans; + if(Metadata.ATA?.Identify != null) { chkATA.Checked = true; @@ -682,6 +851,7 @@ namespace apprepodbmgr.Eto txtPCIProduct.Visible = true; txtPCIVendor.Text = $"0x{Metadata.PCI.VendorID:X4}"; txtPCIProduct.Text = $"0x{Metadata.PCI.DeviceID:X4}"; + if(Metadata.PCI.Configuration != null) { frmPCIConfiguration.Visible = true; @@ -716,23 +886,31 @@ namespace apprepodbmgr.Eto lstPCMCIACIS.Add(Metadata.PCMCIA.CIS); } - if(Metadata.PCMCIA.Compliance != null) txtCompliance.Text = Metadata.PCMCIA.Compliance; + if(Metadata.PCMCIA.Compliance != null) + txtCompliance.Text = Metadata.PCMCIA.Compliance; + if(Metadata.PCMCIA.ManufacturerCodeSpecified) - txtMfgCode.Text = - $"0x{Metadata.PCMCIA.ManufacturerCode:X4}"; + txtMfgCode.Text = $"0x{Metadata.PCMCIA.ManufacturerCode:X4}"; + if(Metadata.PCMCIA.CardCodeSpecified) txtCardCode.Text = $"0x{Metadata.PCMCIA.CardCode:X4}"; + if(Metadata.PCMCIA.Manufacturer != null) txtPCMCIAManufacturer.Text = Metadata.PCMCIA.Manufacturer; + if(Metadata.PCMCIA.ProductName != null) txtPCMCIAProductName.Text = Metadata.PCMCIA.ProductName; + if(Metadata.PCMCIA.AdditionalInformation != null) { lblAdditionalInformation.Visible = true; treeAdditionalInformation.Visible = true; foreach(string addinfo in Metadata.PCMCIA.AdditionalInformation) - lstAdditionalInformation.Add(new StringEntry {str = addinfo}); + lstAdditionalInformation.Add(new StringEntry + { + str = addinfo + }); } } @@ -801,6 +979,7 @@ namespace apprepodbmgr.Eto txtUSBProduct.Visible = true; txtUSBVendor.Text = $"0x{Metadata.USB.VendorID:X4}"; txtUSBProduct.Text = $"0x{Metadata.USB.ProductID:X4}"; + if(Metadata.USB.Descriptors != null) { frmDescriptors.Visible = true; @@ -815,9 +994,15 @@ namespace apprepodbmgr.Eto lstMAM.Add(Metadata.MAM); } - if(Metadata.HeadsSpecified) spHeads.Value = Metadata.Heads; - if(Metadata.CylindersSpecified) spCylinders.Value = Metadata.Cylinders; - if(Metadata.SectorsPerTrackSpecified) spSectors.Value = Metadata.SectorsPerTrack; + if(Metadata.HeadsSpecified) + spHeads.Value = Metadata.Heads; + + if(Metadata.CylindersSpecified) + spCylinders.Value = Metadata.Cylinders; + + if(Metadata.SectorsPerTrackSpecified) + spSectors.Value = Metadata.SectorsPerTrack; + if(Metadata.Track != null) { chkTracks.Checked = true; @@ -826,10 +1011,13 @@ namespace apprepodbmgr.Eto treeTracks.DataStore = lstTracks; // TODO: Really needed? } - if(Metadata.CopyProtection != null) txtCopyProtection.Text = Metadata.CopyProtection; - if(Metadata.Dimensions != null) + if(Metadata.CopyProtection != null) + txtCopyProtection.Text = Metadata.CopyProtection; + + if(Metadata.Dimensions != null) { chkDimensions.Checked = true; + if(Metadata.Dimensions.DiameterSpecified) { chkRound.Checked = true; @@ -869,8 +1057,11 @@ namespace apprepodbmgr.Eto treeDumpHardware.DataStore = lstDumpHw; // TODO: Really needed? } - if(Metadata.DiskType != null) txtMediaType.Text = Metadata.DiskType; - if(Metadata.DiskSubType != null) txtMediaSubtype.Text = Metadata.DiskSubType; + if(Metadata.DiskType != null) + txtMediaType.Text = Metadata.DiskType; + + if(Metadata.DiskSubType != null) + txtMediaSubtype.Text = Metadata.DiskSubType; } protected void OnChkSequenceToggled(object sender, EventArgs e) @@ -891,7 +1082,9 @@ namespace apprepodbmgr.Eto { chkRound.Visible = chkDimensions.Checked.Value; stkThickness.Visible = chkDimensions.Checked.Value; - if(chkDimensions.Checked.Value) OnChkRoundToggled(sender, e); + + if(chkDimensions.Checked.Value) + OnChkRoundToggled(sender, e); else { stkDiameter.Visible = false; @@ -939,12 +1132,14 @@ namespace apprepodbmgr.Eto protected void OnBtnRemovePartitionClicked(object sender, EventArgs e) { - if(treePartitions.SelectedItem != null) lstPartitions.Remove((PartitionType)treePartitions.SelectedItem); + if(treePartitions.SelectedItem != null) + lstPartitions.Remove((PartitionType)treePartitions.SelectedItem); } protected void OnBtnEditPartitionClicked(object sender, EventArgs e) { - if(treePartitions.SelectedItem == null) return; + if(treePartitions.SelectedItem == null) + return; partitionIter = (PartitionType)treePartitions.SelectedItem; @@ -973,22 +1168,26 @@ namespace apprepodbmgr.Eto if(!int.TryParse(txtPartitionStart.Text, out int temp)) { MessageBox.Show("Partition start must be a number", MessageBoxType.Error); + return; } if(!int.TryParse(txtPartitionEnd.Text, out int temp2)) { MessageBox.Show("Partition end must be a number", MessageBoxType.Error); + return; } if(temp2 <= temp) { MessageBox.Show("Partition must end after start, and be bigger than 1 sector", MessageBoxType.Error); + return; } - if(editingPartition) lstPartitions.Remove(partitionIter); + if(editingPartition) + lstPartitions.Remove(partitionIter); partitionIter = new PartitionType { @@ -999,6 +1198,7 @@ namespace apprepodbmgr.Eto Name = txtPartitionName.Text, Description = txtPartitionDescription.Text }; + if(((ObservableCollection)treeFilesystems.DataStore).Count > 0) partitionIter.FileSystems = ((ObservableCollection)treeFilesystems.DataStore).ToArray(); @@ -1037,21 +1237,27 @@ namespace apprepodbmgr.Eto protected void OnBtnRemoveFilesystemClicked(object sender, EventArgs e) { if(treeFilesystems.SelectedItem != null) - ((ObservableCollection)treeFilesystems.DataStore).Remove((FileSystemType)treeFilesystems - .SelectedItem); + ((ObservableCollection)treeFilesystems.DataStore). + Remove((FileSystemType)treeFilesystems.SelectedItem); } protected void OnBtnEditFilesystemClicked(object sender, EventArgs e) { - if(treeFilesystems.SelectedItem == null) return; + if(treeFilesystems.SelectedItem == null) + return; filesystemIter = (FileSystemType)treeFilesystems.SelectedItem; - dlgFilesystem _dlgFilesystem = new dlgFilesystem {Metadata = filesystemIter}; + var _dlgFilesystem = new dlgFilesystem + { + Metadata = filesystemIter + }; + _dlgFilesystem.FillFields(); _dlgFilesystem.ShowModal(this); - if(!_dlgFilesystem.Modified) return; + if(!_dlgFilesystem.Modified) + return; ((ObservableCollection)treeFilesystems.DataStore).Remove(filesystemIter); ((ObservableCollection)treeFilesystems.DataStore).Add(_dlgFilesystem.Metadata); @@ -1059,7 +1265,7 @@ namespace apprepodbmgr.Eto protected void OnBtnAddFilesystemClicked(object sender, EventArgs e) { - dlgFilesystem _dlgFilesystem = new dlgFilesystem(); + var _dlgFilesystem = new dlgFilesystem(); _dlgFilesystem.ShowModal(this); if(_dlgFilesystem.Modified) @@ -1090,12 +1296,14 @@ namespace apprepodbmgr.Eto protected void OnBtnRemoveHardwareClicked(object sender, EventArgs e) { - if(treeDumpHardware.SelectedItem != null) lstDumpHw.Remove((DumpHardwareType)treeDumpHardware.SelectedItem); + if(treeDumpHardware.SelectedItem != null) + lstDumpHw.Remove((DumpHardwareType)treeDumpHardware.SelectedItem); } protected void OnBtnEditHardwareClicked(object sender, EventArgs e) { - if(treeDumpHardware.SelectedItem == null) return; + if(treeDumpHardware.SelectedItem == null) + return; dumpHwIter = (DumpHardwareType)treeDumpHardware.SelectedItem; @@ -1104,6 +1312,7 @@ namespace apprepodbmgr.Eto txtHWRevision.Text = dumpHwIter.Revision; txtHWFirmware.Text = dumpHwIter.Firmware; txtHWSerial.Text = dumpHwIter.Serial; + if(dumpHwIter.Software != null) { txtDumpName.Text = dumpHwIter.Software.Name; @@ -1125,7 +1334,8 @@ namespace apprepodbmgr.Eto protected void OnBtnApplyHardwareClicked(object sender, EventArgs e) { - if(editingDumpHw) lstDumpHw.Remove(dumpHwIter); + if(editingDumpHw) + lstDumpHw.Remove(dumpHwIter); dumpHwIter = new DumpHardwareType { @@ -1135,7 +1345,9 @@ namespace apprepodbmgr.Eto Firmware = txtHWFirmware.Text, Serial = txtHWSerial.Text }; - if(!string.IsNullOrWhiteSpace(txtDumpName.Text) || !string.IsNullOrWhiteSpace(txtDumpVersion.Text) || + + if(!string.IsNullOrWhiteSpace(txtDumpName.Text) || + !string.IsNullOrWhiteSpace(txtDumpVersion.Text) || !string.IsNullOrWhiteSpace(txtDumpOS.Text)) dumpHwIter.Software = new SoftwareType { @@ -1143,6 +1355,7 @@ namespace apprepodbmgr.Eto Version = txtDumpVersion.Text, OperatingSystem = txtDumpOS.Text }; + if(((ObservableCollection)treeExtents.DataStore).Count > 0) dumpHwIter.Extents = ((ObservableCollection)treeExtents.DataStore).ToArray(); @@ -1184,19 +1397,14 @@ namespace apprepodbmgr.Eto ((ObservableCollection)treeExtents.DataStore).Remove((ExtentType)treeExtents.SelectedItem); } - protected void OnBtnAddExtentClicked(object sender, EventArgs e) - { + protected void OnBtnAddExtentClicked(object sender, EventArgs e) => ((ObservableCollection)treeExtents.DataStore).Add(new ExtentType { Start = (ulong)spExtentStart.Value, End = (ulong)spExtentEnd.Value }); - } - protected void OnBtnCancelClicked(object sender, EventArgs e) - { - Close(); - } + protected void OnBtnCancelClicked(object sender, EventArgs e) => Close(); protected void OnBtnSaveClicked(object sender, EventArgs e) { @@ -1204,6 +1412,7 @@ namespace apprepodbmgr.Eto if(string.IsNullOrEmpty(txtFormat.Text)) { MessageBox.Show("Image format cannot be null", MessageBoxType.Error); + return; } @@ -1212,49 +1421,58 @@ namespace apprepodbmgr.Eto if(spSequence.Value < 1) { MessageBox.Show("Media sequence must be bigger than 0", MessageBoxType.Error); + return; } if(spTotalMedia.Value < 1) { MessageBox.Show("Total medias must be bigger than 0", MessageBoxType.Error); + return; } if(spSequence.Value > spTotalMedia.Value) { MessageBox.Show("Media sequence cannot be bigger than total medias", MessageBoxType.Error); + return; } } - if(string.IsNullOrEmpty(txtBlocks.Text) || !long.TryParse(txtBlocks.Text, out long ltmp)) + if(string.IsNullOrEmpty(txtBlocks.Text) || + !long.TryParse(txtBlocks.Text, out long ltmp)) { MessageBox.Show("Blocks must be a number", MessageBoxType.Error); + return; } if(ltmp < 1) { MessageBox.Show("Blocks must be bigger than 0", MessageBoxType.Error); + return; } if(spPhysicalBlockSize.Value < 1) { MessageBox.Show("Physical Block Size must be bigger than 0", MessageBoxType.Error); + return; } if(spLogicalBlockSize.Value < 1) { MessageBox.Show("Logical Block Size must be bigger than 0", MessageBoxType.Error); + return; } if(spPhysicalBlockSize.Value < spLogicalBlockSize.Value) { MessageBox.Show("Physical Block Size must be bigger than Logical Block Size", MessageBoxType.Error); + return; } @@ -1265,6 +1483,7 @@ namespace apprepodbmgr.Eto if(spDiameter.Value <= 0) { MessageBox.Show("Diameter must be bigger than 0", MessageBoxType.Error); + return; } } @@ -1273,12 +1492,14 @@ namespace apprepodbmgr.Eto if(spHeight.Value <= 0) { MessageBox.Show("Height must be bigger than 0", MessageBoxType.Error); + return; } if(spWidth.Value <= 0) { MessageBox.Show("Width must be bigger than 0", MessageBoxType.Error); + return; } } @@ -1286,6 +1507,7 @@ namespace apprepodbmgr.Eto if(spThickness.Value <= 0) { MessageBox.Show("Thickness must be bigger than 0", MessageBoxType.Error); + return; } } @@ -1295,50 +1517,60 @@ namespace apprepodbmgr.Eto if(string.IsNullOrWhiteSpace(txtPCIVendor.Text)) { MessageBox.Show("PCI Vendor ID must be set", MessageBoxType.Error); + return; } if(string.IsNullOrWhiteSpace(txtPCIProduct.Text)) { MessageBox.Show("PCI Product ID must be set", MessageBoxType.Error); + return; } try { - if(Convert.ToInt32(txtPCIVendor.Text, 16) < 0 || Convert.ToInt32(txtPCIVendor.Text, 16) > 0xFFFF) + if(Convert.ToInt32(txtPCIVendor.Text, 16) < 0 || + Convert.ToInt32(txtPCIVendor.Text, 16) > 0xFFFF) { MessageBox.Show("PCI Vendor ID must be between 0x0000 and 0xFFFF", MessageBoxType.Error); + return; } } catch(FormatException) { MessageBox.Show("PCI Vendor ID must be a number in hexadecimal format", MessageBoxType.Error); + return; } catch(OverflowException) { MessageBox.Show("PCI Vendor ID must not be negative", MessageBoxType.Error); + return; } try { - if(Convert.ToInt32(txtPCIProduct.Text, 16) < 0 || Convert.ToInt32(txtPCIProduct.Text, 16) > 0xFFFF) + if(Convert.ToInt32(txtPCIProduct.Text, 16) < 0 || + Convert.ToInt32(txtPCIProduct.Text, 16) > 0xFFFF) { MessageBox.Show("PCI Product ID must be between 0x0000 and 0xFFFF", MessageBoxType.Error); + return; } } catch(FormatException) { MessageBox.Show("PCI Product ID must be a number in hexadecimal format", MessageBoxType.Error); + return; } catch(OverflowException) { MessageBox.Show("PCI Product ID must not be negative", MessageBoxType.Error); + return; } } @@ -1348,21 +1580,25 @@ namespace apprepodbmgr.Eto if(string.IsNullOrWhiteSpace(txtPCMCIAManufacturer.Text)) { MessageBox.Show("PCMCIA Manufacturer Code must be set", MessageBoxType.Error); + return; } if(string.IsNullOrWhiteSpace(txtCardCode.Text)) { MessageBox.Show("PCMCIA Card Code must be set", MessageBoxType.Error); + return; } try { - if(Convert.ToInt32(txtMfgCode.Text, 16) < 0 || Convert.ToInt32(txtMfgCode.Text, 16) > 0xFFFF) + if(Convert.ToInt32(txtMfgCode.Text, 16) < 0 || + Convert.ToInt32(txtMfgCode.Text, 16) > 0xFFFF) { MessageBox.Show("PCMCIA Manufacturer Code must be between 0x0000 and 0xFFFF", MessageBoxType.Error); + return; } } @@ -1370,30 +1606,36 @@ namespace apprepodbmgr.Eto { MessageBox.Show("PCMCIA Manufacturer Code must be a number in hexadecimal format", MessageBoxType.Error); + return; } catch(OverflowException) { MessageBox.Show("PCMCIA Manufacturer Code must not be negative", MessageBoxType.Error); + return; } try { - if(Convert.ToInt32(txtCardCode.Text, 16) < 0 || Convert.ToInt32(txtCardCode.Text, 16) > 0xFFFF) + if(Convert.ToInt32(txtCardCode.Text, 16) < 0 || + Convert.ToInt32(txtCardCode.Text, 16) > 0xFFFF) { MessageBox.Show("PCMCIA Card Code must be between 0x0000 and 0xFFFF", MessageBoxType.Error); + return; } } catch(FormatException) { MessageBox.Show("PCMCIA Card Code must be a number in hexadecimal format", MessageBoxType.Error); + return; } catch(OverflowException) { MessageBox.Show("PCMCIA Card Code must not be negative", MessageBoxType.Error); + return; } } @@ -1403,50 +1645,60 @@ namespace apprepodbmgr.Eto if(string.IsNullOrWhiteSpace(txtUSBVendor.Text)) { MessageBox.Show("USB Vendor ID must be set", MessageBoxType.Error); + return; } if(string.IsNullOrWhiteSpace(txtUSBProduct.Text)) { MessageBox.Show("USB Product ID must be set", MessageBoxType.Error); + return; } try { - if(Convert.ToInt32(txtUSBVendor.Text, 16) < 0 || Convert.ToInt32(txtUSBVendor.Text, 16) > 0xFFFF) + if(Convert.ToInt32(txtUSBVendor.Text, 16) < 0 || + Convert.ToInt32(txtUSBVendor.Text, 16) > 0xFFFF) { MessageBox.Show("USB Vendor ID must be between 0x0000 and 0xFFFF", MessageBoxType.Error); + return; } } catch(FormatException) { MessageBox.Show("USB Vendor ID must be a number in hexadecimal format", MessageBoxType.Error); + return; } catch(OverflowException) { MessageBox.Show("USB Vendor ID must not be negative", MessageBoxType.Error); + return; } try { - if(Convert.ToInt32(txtUSBProduct.Text, 16) < 0 || Convert.ToInt32(txtUSBProduct.Text, 16) > 0xFFFF) + if(Convert.ToInt32(txtUSBProduct.Text, 16) < 0 || + Convert.ToInt32(txtUSBProduct.Text, 16) > 0xFFFF) { MessageBox.Show("USB Product ID must be between 0x0000 and 0xFFFF", MessageBoxType.Error); + return; } } catch(FormatException) { MessageBox.Show("USB Product ID must be a number in hexadecimal format", MessageBoxType.Error); + return; } catch(OverflowException) { MessageBox.Show("USB Product ID must not be negative", MessageBoxType.Error); + return; } } @@ -1455,13 +1707,22 @@ namespace apprepodbmgr.Eto if(lstDumpHw.Count < 1) { MessageBox.Show("If dump hardware is known at least an entry must be created"); + return; } #endregion Sanity checks - Metadata = new BlockMediaType {Image = new ImageType {Value = txtImage.Text, format = txtFormat.Text}}; + Metadata = new BlockMediaType + { + Image = new ImageType + { + Value = txtImage.Text, + format = txtFormat.Text + } + }; - if(!string.IsNullOrWhiteSpace(txtOffset.Text) && long.TryParse(txtOffset.Text, out ltmp)) + if(!string.IsNullOrWhiteSpace(txtOffset.Text) && + long.TryParse(txtOffset.Text, out ltmp)) { Metadata.Image.offsetSpecified = true; Metadata.Image.offset = long.Parse(txtOffset.Text); @@ -1479,6 +1740,7 @@ namespace apprepodbmgr.Eto MediaSequence = (int)spSequence.Value, TotalMedia = (int)spTotalMedia.Value }; + if(spSide.Value > 0) { Metadata.Sequence.SideSpecified = true; @@ -1492,11 +1754,20 @@ namespace apprepodbmgr.Eto } } - if(!string.IsNullOrWhiteSpace(txtManufacturer.Text)) Metadata.Manufacturer = txtManufacturer.Text; - if(!string.IsNullOrWhiteSpace(txtModel.Text)) Metadata.Model = txtModel.Text; - if(!string.IsNullOrWhiteSpace(txtSerial.Text)) Metadata.Serial = txtSerial.Text; - if(!string.IsNullOrWhiteSpace(txtFirmware.Text)) Metadata.Firmware = txtFirmware.Text; - if(!string.IsNullOrWhiteSpace(txtInterface.Text)) Metadata.Interface = txtInterface.Text; + if(!string.IsNullOrWhiteSpace(txtManufacturer.Text)) + Metadata.Manufacturer = txtManufacturer.Text; + + if(!string.IsNullOrWhiteSpace(txtModel.Text)) + Metadata.Model = txtModel.Text; + + if(!string.IsNullOrWhiteSpace(txtSerial.Text)) + Metadata.Serial = txtSerial.Text; + + if(!string.IsNullOrWhiteSpace(txtFirmware.Text)) + Metadata.Firmware = txtFirmware.Text; + + if(!string.IsNullOrWhiteSpace(txtInterface.Text)) + Metadata.Interface = txtInterface.Text; Metadata.PhysicalBlockSize = (int)spPhysicalBlockSize.Value; Metadata.LogicalBlockSize = (int)spLogicalBlockSize.Value; @@ -1505,32 +1776,44 @@ namespace apprepodbmgr.Eto Metadata.TapeInformation = tapeInformation; Metadata.Scans = scans; - if(chkATA.Checked.Value && lstAta.Count == 1) Metadata.ATA = new ATAType {Identify = lstAta[0]}; + if(chkATA.Checked.Value && + lstAta.Count == 1) + Metadata.ATA = new ATAType + { + Identify = lstAta[0] + }; if(chkPCI.Checked.Value) { Metadata.PCI = new PCIType { - VendorID = Convert.ToUInt16(txtPCIVendor.Text, 16), + VendorID = Convert.ToUInt16(txtPCIVendor.Text, 16), DeviceID = Convert.ToUInt16(txtPCIProduct.Text, 16) }; - if(lstPCIConfiguration.Count == 1) Metadata.PCI.Configuration = lstPCIConfiguration[0]; + if(lstPCIConfiguration.Count == 1) + Metadata.PCI.Configuration = lstPCIConfiguration[0]; - if(lstPCIOptionROM.Count == 1) Metadata.PCI.ExpansionROM = lstPCIOptionROM[0]; + if(lstPCIOptionROM.Count == 1) + Metadata.PCI.ExpansionROM = lstPCIOptionROM[0]; } if(chkPCMCIA.Checked.Value) { Metadata.PCMCIA = new PCMCIAType(); - if(lstPCMCIACIS.Count == 1) Metadata.PCMCIA.CIS = lstPCMCIACIS[0]; + if(lstPCMCIACIS.Count == 1) + Metadata.PCMCIA.CIS = lstPCMCIACIS[0]; + + if(!string.IsNullOrWhiteSpace(txtCompliance.Text)) + Metadata.PCMCIA.Compliance = txtCompliance.Text; - if(!string.IsNullOrWhiteSpace(txtCompliance.Text)) Metadata.PCMCIA.Compliance = txtCompliance.Text; if(!string.IsNullOrWhiteSpace(txtPCMCIAManufacturer.Text)) Metadata.PCMCIA.Manufacturer = txtPCMCIAManufacturer.Text; + if(!string.IsNullOrWhiteSpace(txtPCMCIAProductName.Text)) Metadata.PCMCIA.ProductName = txtPCMCIAProductName.Text; + if(!string.IsNullOrWhiteSpace(txtMfgCode.Text)) { Metadata.PCMCIA.ManufacturerCodeSpecified = true; @@ -1546,7 +1829,10 @@ namespace apprepodbmgr.Eto if(lstAdditionalInformation.Count > 0) { List addinfos = new List(); - foreach(StringEntry entry in lstAdditionalInformation) addinfos.Add(entry.str); + + foreach(StringEntry entry in lstAdditionalInformation) + addinfos.Add(entry.str); + Metadata.PCMCIA.AdditionalInformation = addinfos.ToArray(); } } @@ -1555,36 +1841,55 @@ namespace apprepodbmgr.Eto { Metadata.SecureDigital = new SecureDigitalType(); - if(lstCID.Count == 1) Metadata.SecureDigital.CID = lstCID[0]; - if(lstCSD.Count == 1) Metadata.SecureDigital.CSD = lstCSD[0]; - if(lstECSD.Count == 1) Metadata.MultiMediaCard.ExtendedCSD = lstECSD[0]; + if(lstCID.Count == 1) + Metadata.SecureDigital.CID = lstCID[0]; + + if(lstCSD.Count == 1) + Metadata.SecureDigital.CSD = lstCSD[0]; + + if(lstECSD.Count == 1) + Metadata.MultiMediaCard.ExtendedCSD = lstECSD[0]; } if(chkSCSI.Checked.Value) { Metadata.SCSI = new SCSIType(); - if(lstInquiry.Count == 1) Metadata.SCSI.Inquiry = lstInquiry[0]; - if(lstModeSense.Count == 1) Metadata.SCSI.ModeSense = lstModeSense[0]; - if(lstModeSense10.Count == 1) Metadata.SCSI.ModeSense10 = lstModeSense10[0]; - if(lstLogSense.Count == 1) Metadata.SCSI.LogSense = lstLogSense[0]; - if(lstEVPDs.Count > 0) Metadata.SCSI.EVPD = lstEVPDs.ToArray(); + if(lstInquiry.Count == 1) + Metadata.SCSI.Inquiry = lstInquiry[0]; + + if(lstModeSense.Count == 1) + Metadata.SCSI.ModeSense = lstModeSense[0]; + + if(lstModeSense10.Count == 1) + Metadata.SCSI.ModeSense10 = lstModeSense10[0]; + + if(lstLogSense.Count == 1) + Metadata.SCSI.LogSense = lstLogSense[0]; + + if(lstEVPDs.Count > 0) + Metadata.SCSI.EVPD = lstEVPDs.ToArray(); } if(chkUSB.Checked.Value) { Metadata.USB = new USBType { - VendorID = Convert.ToUInt16(txtUSBVendor.Text, 16), + VendorID = Convert.ToUInt16(txtUSBVendor.Text, 16), ProductID = Convert.ToUInt16(txtUSBProduct.Text, 16) }; - if(lstUSBDescriptors.Count == 1) Metadata.USB.Descriptors = lstUSBDescriptors[0]; + if(lstUSBDescriptors.Count == 1) + Metadata.USB.Descriptors = lstUSBDescriptors[0]; } - if(chkMAM.Checked.Value && lstMAM.Count == 1) Metadata.MAM = lstMAM[0]; + if(chkMAM.Checked.Value && + lstMAM.Count == 1) + Metadata.MAM = lstMAM[0]; - if(spHeads.Value > 0 && spCylinders.Value > 0 && spSectors.Value > 0) + if(spHeads.Value > 0 && + spCylinders.Value > 0 && + spSectors.Value > 0) { Metadata.HeadsSpecified = true; Metadata.CylindersSpecified = true; @@ -1594,13 +1899,16 @@ namespace apprepodbmgr.Eto Metadata.SectorsPerTrack = (long)spSectors.Value; } - if(lstTracks.Count > 0) Metadata.Track = lstTracks.ToArray(); + if(lstTracks.Count > 0) + Metadata.Track = lstTracks.ToArray(); - if(!string.IsNullOrWhiteSpace(txtCopyProtection.Text)) Metadata.CopyProtection = txtCopyProtection.Text; + if(!string.IsNullOrWhiteSpace(txtCopyProtection.Text)) + Metadata.CopyProtection = txtCopyProtection.Text; if(chkDimensions.Checked.Value) { Metadata.Dimensions = new DimensionsType(); + if(chkRound.Checked.Value) { Metadata.Dimensions.DiameterSpecified = true; @@ -1617,12 +1925,18 @@ namespace apprepodbmgr.Eto Metadata.Dimensions.Thickness = spThickness.Value; } - if(lstPartitions.Count > 0) Metadata.FileSystemInformation = lstPartitions.ToArray(); + if(lstPartitions.Count > 0) + Metadata.FileSystemInformation = lstPartitions.ToArray(); - if(chkDumpHardware.Checked.Value && lstDumpHw.Count > 0) Metadata.DumpHardwareArray = lstDumpHw.ToArray(); + if(chkDumpHardware.Checked.Value && + lstDumpHw.Count > 0) + Metadata.DumpHardwareArray = lstDumpHw.ToArray(); - if(!string.IsNullOrWhiteSpace(txtMediaType.Text)) Metadata.DiskType = txtMediaType.Text; - if(!string.IsNullOrWhiteSpace(txtMediaSubtype.Text)) Metadata.DiskSubType = txtMediaSubtype.Text; + if(!string.IsNullOrWhiteSpace(txtMediaType.Text)) + Metadata.DiskType = txtMediaType.Text; + + if(!string.IsNullOrWhiteSpace(txtMediaSubtype.Text)) + Metadata.DiskSubType = txtMediaSubtype.Text; Modified = true; Close(); diff --git a/apprepodbmgr.Eto/dlgFilesystem.xeto.cs b/apprepodbmgr.Eto/dlgFilesystem.xeto.cs index ee68b08..4adace6 100644 --- a/apprepodbmgr.Eto/dlgFilesystem.xeto.cs +++ b/apprepodbmgr.Eto/dlgFilesystem.xeto.cs @@ -46,9 +46,12 @@ namespace apprepodbmgr.Eto public void FillFields() { - if(Metadata == null) return; + if(Metadata == null) + return; + + if(Metadata.Type != null) + txtType.Text = Metadata.Type; - if(Metadata.Type != null) txtType.Text = Metadata.Type; if(Metadata.CreationDateSpecified) { chkCreationDate.Checked = true; @@ -70,14 +73,25 @@ namespace apprepodbmgr.Eto cldBackupDate.Value = Metadata.BackupDate; } - spClusterSize.Value = Metadata.ClusterSize; - txtClusters.Text = Metadata.Clusters.ToString(); - if(Metadata.FilesSpecified) txtFiles.Text = Metadata.Files.ToString(); - chkBootable.Checked = Metadata.Bootable; - if(Metadata.VolumeSerial != null) txtSerial.Text = Metadata.VolumeSerial; - if(Metadata.VolumeName != null) txtLabel.Text = Metadata.VolumeName; - if(Metadata.FreeClustersSpecified) txtFreeClusters.Text = Metadata.FreeClusters.ToString(); - chkDirty.Checked = Metadata.Dirty; + spClusterSize.Value = Metadata.ClusterSize; + txtClusters.Text = Metadata.Clusters.ToString(); + + if(Metadata.FilesSpecified) + txtFiles.Text = Metadata.Files.ToString(); + + chkBootable.Checked = Metadata.Bootable; + + if(Metadata.VolumeSerial != null) + txtSerial.Text = Metadata.VolumeSerial; + + if(Metadata.VolumeName != null) + txtLabel.Text = Metadata.VolumeName; + + if(Metadata.FreeClustersSpecified) + txtFreeClusters.Text = Metadata.FreeClusters.ToString(); + + chkDirty.Checked = Metadata.Dirty; + if(Metadata.ExpirationDateSpecified) { chkExpirationDate.Checked = true; @@ -92,37 +106,36 @@ namespace apprepodbmgr.Eto cldEffectiveDate.Value = Metadata.EffectiveDate; } - if(Metadata.SystemIdentifier != null) txtSysId.Text = Metadata.SystemIdentifier; - if(Metadata.VolumeSetIdentifier != null) txtVolId.Text = Metadata.VolumeSetIdentifier; - if(Metadata.PublisherIdentifier != null) txtPubId.Text = Metadata.PublisherIdentifier; - if(Metadata.DataPreparerIdentifier != null) txtDataId.Text = Metadata.DataPreparerIdentifier; - if(Metadata.ApplicationIdentifier != null) txtAppId.Text = Metadata.ApplicationIdentifier; + if(Metadata.SystemIdentifier != null) + txtSysId.Text = Metadata.SystemIdentifier; + + if(Metadata.VolumeSetIdentifier != null) + txtVolId.Text = Metadata.VolumeSetIdentifier; + + if(Metadata.PublisherIdentifier != null) + txtPubId.Text = Metadata.PublisherIdentifier; + + if(Metadata.DataPreparerIdentifier != null) + txtDataId.Text = Metadata.DataPreparerIdentifier; + + if(Metadata.ApplicationIdentifier != null) + txtAppId.Text = Metadata.ApplicationIdentifier; } - protected void OnChkCreationDateToggled(object sender, EventArgs e) - { + protected void OnChkCreationDateToggled(object sender, EventArgs e) => cldCreationDate.Enabled = chkCreationDate.Checked.Value; - } - protected void OnChkModificationDateToggled(object sender, EventArgs e) - { + protected void OnChkModificationDateToggled(object sender, EventArgs e) => cldModificationDate.Enabled = chkModificationDate.Checked.Value; - } - protected void OnChkEffectiveDateToggled(object sender, EventArgs e) - { + protected void OnChkEffectiveDateToggled(object sender, EventArgs e) => cldEffectiveDate.Enabled = chkEffectiveDate.Checked.Value; - } - protected void OnChkExpirationDateToggled(object sender, EventArgs e) - { + protected void OnChkExpirationDateToggled(object sender, EventArgs e) => cldExpirationDate.Enabled = chkExpirationDate.Checked.Value; - } - protected void OnChkBackupDateToggled(object sender, EventArgs e) - { + protected void OnChkBackupDateToggled(object sender, EventArgs e) => cldBackupDate.Enabled = chkBackupDate.Checked.Value; - } protected void OnBtnCancelClicked(object sender, EventArgs e) { @@ -135,26 +148,36 @@ namespace apprepodbmgr.Eto if(string.IsNullOrWhiteSpace(txtType.Text)) MessageBox.Show("Filesystem type cannot be empty", MessageBoxType.Error); - if(spClusterSize.Value < 1) MessageBox.Show("Clusters must be bigger than 0 bytes", MessageBoxType.Error); + if(spClusterSize.Value < 1) + MessageBox.Show("Clusters must be bigger than 0 bytes", MessageBoxType.Error); if(!long.TryParse(txtClusters.Text, out long temp)) MessageBox.Show("Clusters must be a number", MessageBoxType.Error); - if(temp < 1) MessageBox.Show("Filesystem must have more than 0 clusters", MessageBoxType.Error); + if(temp < 1) + MessageBox.Show("Filesystem must have more than 0 clusters", MessageBoxType.Error); - if(!string.IsNullOrWhiteSpace(txtFiles.Text) && !long.TryParse(txtFiles.Text, out temp)) + if(!string.IsNullOrWhiteSpace(txtFiles.Text) && + !long.TryParse(txtFiles.Text, out temp)) MessageBox.Show("Files must be a number, or empty for unknown", MessageBoxType.Error); - if(!string.IsNullOrWhiteSpace(txtFiles.Text) && temp < 0) + if(!string.IsNullOrWhiteSpace(txtFiles.Text) && + temp < 0) MessageBox.Show("Files must be positive", MessageBoxType.Error); - if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text) && !long.TryParse(txtFreeClusters.Text, out temp)) + if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text) && + !long.TryParse(txtFreeClusters.Text, out temp)) MessageBox.Show("Free clusters must be a number or empty for unknown", MessageBoxType.Error); - if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text) && temp < 0) + if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text) && + temp < 0) MessageBox.Show("Free clusters must be positive", MessageBoxType.Error); - Metadata = new FileSystemType {Type = txtType.Text}; + Metadata = new FileSystemType + { + Type = txtType.Text + }; + if(chkCreationDate.Checked.Value) { Metadata.CreationDateSpecified = true; @@ -175,15 +198,21 @@ namespace apprepodbmgr.Eto Metadata.ClusterSize = (int)spClusterSize.Value; Metadata.Clusters = long.Parse(txtClusters.Text); + if(!string.IsNullOrWhiteSpace(txtFiles.Text)) { Metadata.FilesSpecified = true; Metadata.Files = long.Parse(txtFiles.Text); } - Metadata.Bootable = chkBootable.Checked.Value; - if(!string.IsNullOrWhiteSpace(txtSerial.Text)) Metadata.VolumeSerial = txtSerial.Text; - if(!string.IsNullOrWhiteSpace(txtLabel.Text)) Metadata.VolumeName = txtLabel.Text; + Metadata.Bootable = chkBootable.Checked.Value; + + if(!string.IsNullOrWhiteSpace(txtSerial.Text)) + Metadata.VolumeSerial = txtSerial.Text; + + if(!string.IsNullOrWhiteSpace(txtLabel.Text)) + Metadata.VolumeName = txtLabel.Text; + if(!string.IsNullOrWhiteSpace(txtFreeClusters.Text)) { Metadata.FreeClustersSpecified = true; @@ -191,6 +220,7 @@ namespace apprepodbmgr.Eto } Metadata.Dirty = chkDirty.Checked.Value; + if(chkExpirationDate.Checked.Value) { Metadata.ExpirationDateSpecified = true; @@ -203,11 +233,20 @@ namespace apprepodbmgr.Eto Metadata.EffectiveDate = cldEffectiveDate.Value.Value; } - if(!string.IsNullOrWhiteSpace(txtSysId.Text)) Metadata.SystemIdentifier = txtSysId.Text; - if(!string.IsNullOrWhiteSpace(txtVolId.Text)) Metadata.VolumeSetIdentifier = txtVolId.Text; - if(!string.IsNullOrWhiteSpace(txtPubId.Text)) Metadata.PublisherIdentifier = txtPubId.Text; - if(!string.IsNullOrWhiteSpace(txtDataId.Text)) Metadata.DataPreparerIdentifier = txtDataId.Text; - if(!string.IsNullOrWhiteSpace(txtAppId.Text)) Metadata.ApplicationIdentifier = txtAppId.Text; + if(!string.IsNullOrWhiteSpace(txtSysId.Text)) + Metadata.SystemIdentifier = txtSysId.Text; + + if(!string.IsNullOrWhiteSpace(txtVolId.Text)) + Metadata.VolumeSetIdentifier = txtVolId.Text; + + if(!string.IsNullOrWhiteSpace(txtPubId.Text)) + Metadata.PublisherIdentifier = txtPubId.Text; + + if(!string.IsNullOrWhiteSpace(txtDataId.Text)) + Metadata.DataPreparerIdentifier = txtDataId.Text; + + if(!string.IsNullOrWhiteSpace(txtAppId.Text)) + Metadata.ApplicationIdentifier = txtAppId.Text; Modified = true; Close(); diff --git a/apprepodbmgr.Eto/dlgImportMetadata.xeto.cs b/apprepodbmgr.Eto/dlgImportMetadata.xeto.cs index 0db15b2..f584443 100644 --- a/apprepodbmgr.Eto/dlgImportMetadata.xeto.cs +++ b/apprepodbmgr.Eto/dlgImportMetadata.xeto.cs @@ -22,9 +22,9 @@ namespace apprepodbmgr.Eto Panels maximumPanel; Panels minimumPanel; List operatingSystems; - pnlDescription panelDescription; - pnlStrings panelStrings; - pnlVersions panelVersions; + readonly pnlDescription panelDescription; + readonly pnlStrings panelStrings; + readonly pnlVersions panelVersions; internal string product; internal string publisher; List strings; @@ -75,37 +75,49 @@ namespace apprepodbmgr.Eto foreach(string file in Context.Executables) { - FileStream exeStream = new FileStream(file, FileMode.Open, FileAccess.Read); - MZ mzExe = new MZ(exeStream); - NE neExe = new NE(exeStream); - AtariST stExe = new AtariST(exeStream); - LX lxExe = new LX(exeStream); - COFF coffExe = new COFF(exeStream); - PE peExe = new PE(exeStream); - Geos geosExe = new Geos(exeStream); - ELF elfExe = new ELF(exeStream); + var exeStream = new FileStream(file, FileMode.Open, FileAccess.Read); + var mzExe = new MZ(exeStream); + var neExe = new NE(exeStream); + var stExe = new AtariST(exeStream); + var lxExe = new LX(exeStream); + var coffExe = new COFF(exeStream); + var peExe = new PE(exeStream); + var geosExe = new Geos(exeStream); + var elfExe = new ELF(exeStream); IExecutable recognizedExe; - if(neExe.Recognized) recognizedExe = neExe; - else if(lxExe.Recognized) recognizedExe = lxExe; - else if(peExe.Recognized) recognizedExe = peExe; - else if(mzExe.Recognized) recognizedExe = mzExe; - else if(coffExe.Recognized) recognizedExe = coffExe; - else if(stExe.Recognized) recognizedExe = stExe; - else if(elfExe.Recognized) recognizedExe = elfExe; - else if(geosExe.Recognized) recognizedExe = geosExe; + if(neExe.Recognized) + recognizedExe = neExe; + else if(lxExe.Recognized) + recognizedExe = lxExe; + else if(peExe.Recognized) + recognizedExe = peExe; + else if(mzExe.Recognized) + recognizedExe = mzExe; + else if(coffExe.Recognized) + recognizedExe = coffExe; + else if(stExe.Recognized) + recognizedExe = stExe; + else if(elfExe.Recognized) + recognizedExe = elfExe; + else if(geosExe.Recognized) + recognizedExe = geosExe; else { exeStream.Close(); + continue; } - if(recognizedExe.Strings != null) strings.AddRange(recognizedExe.Strings); + if(recognizedExe.Strings != null) + strings.AddRange(recognizedExe.Strings); foreach(Architecture exeArch in recognizedExe.Architectures) { ArchitecturesTypeArchitecture? arch = ExeArchToSchemaArch(exeArch); - if(arch.HasValue && !architectures.Contains($"{arch.Value}")) + + if(arch.HasValue && + !architectures.Contains($"{arch.Value}")) architectures.Add($"{arch.Value}"); } @@ -125,11 +137,13 @@ namespace apprepodbmgr.Eto versions.Add(exeVersion.FileVersion); versions.Add(exeVersion.ProductVersion); version = exeVersion.ProductVersion; - foreach(KeyValuePair> kvp in exeVersion - .StringsByLanguage) + + foreach(KeyValuePair> kvp in exeVersion. + StringsByLanguage) { if(kvp.Value.TryGetValue("CompanyName", out string tmpValue)) developer = tmpValue; + if(kvp.Value.TryGetValue("ProductName", out string tmpValue2)) product = tmpValue2; } @@ -143,11 +157,13 @@ namespace apprepodbmgr.Eto versions.Add(exeVersion.FileVersion); versions.Add(exeVersion.ProductVersion); version = exeVersion.ProductVersion; - foreach(KeyValuePair> kvp in exeVersion - .StringsByLanguage) + + foreach(KeyValuePair> kvp in exeVersion. + StringsByLanguage) { if(kvp.Value.TryGetValue("CompanyName", out string tmpValue)) developer = tmpValue; + if(kvp.Value.TryGetValue("ProductName", out string tmpValue2)) product = tmpValue2; } @@ -160,12 +176,15 @@ namespace apprepodbmgr.Eto versions.Add(lxExe.WinVersion.FileVersion); versions.Add(lxExe.WinVersion.ProductVersion); version = lxExe.WinVersion.ProductVersion; - foreach(KeyValuePair> kvp in lxExe - .WinVersion - .StringsByLanguage) + + foreach(KeyValuePair> kvp in lxExe.WinVersion. + StringsByLanguage) { - if(kvp.Value.TryGetValue("CompanyName", out string tmpValue)) developer = tmpValue; - if(kvp.Value.TryGetValue("ProductName", out string tmpValue2)) product = tmpValue2; + if(kvp.Value.TryGetValue("CompanyName", out string tmpValue)) + developer = tmpValue; + + if(kvp.Value.TryGetValue("ProductName", out string tmpValue2)) + product = tmpValue2; } } @@ -179,8 +198,11 @@ namespace apprepodbmgr.Eto strings = strings.Distinct().ToList(); strings.Sort(); - if(strings.Count == 0 && minimumPanel == Panels.Strings) minimumPanel = Panels.Versions; - else maximumPanel = Panels.Strings; + if(strings.Count == 0 && + minimumPanel == Panels.Strings) + minimumPanel = Panels.Versions; + else + maximumPanel = Panels.Strings; panelStrings.treeStrings.DataStore = strings; versions = versions.Distinct().ToList(); @@ -194,11 +216,13 @@ namespace apprepodbmgr.Eto foreach(TargetOsEntry osEntry in operatingSystems) { - if(string.IsNullOrEmpty(osEntry.name)) continue; + if(string.IsNullOrEmpty(osEntry.name)) + continue; osEntriesDictionary.TryGetValue(osEntry.name, out List osvers); - if(osvers == null) osvers = new List(); + if(osvers == null) + osvers = new List(); osvers.Add(osEntry.version); osEntriesDictionary.Remove(osEntry.name); @@ -206,38 +230,52 @@ namespace apprepodbmgr.Eto } operatingSystems = new List(); + foreach(KeyValuePair> kvp in osEntriesDictionary.OrderBy(t => t.Key)) { kvp.Value.Sort(); + foreach(string s in kvp.Value.Distinct()) - operatingSystems.Add(new TargetOsEntry {name = kvp.Key, version = s}); + operatingSystems.Add(new TargetOsEntry + { + name = kvp.Key, + version = s + }); } panelVersions.treeOs.DataStore = operatingSystems; - if(versions.Count > 0 || architectures.Count > 0 || operatingSystems.Count > 0) + if(versions.Count > 0 || + architectures.Count > 0 || + operatingSystems.Count > 0) maximumPanel = Panels.Versions; } prgProgress.Visible = false; btnPrevious.Enabled = false; + switch(minimumPanel) { case Panels.Description: pnlPanel.Content = panelDescription; currentPanel = Panels.Description; + break; case Panels.Strings: pnlPanel.Content = panelStrings; currentPanel = Panels.Strings; + break; case Panels.Versions: pnlPanel.Content = panelVersions; currentPanel = Panels.Versions; + break; } - if(currentPanel == maximumPanel) btnNext.Text = "Finish"; + if(currentPanel == maximumPanel) + btnNext.Text = "Finish"; + lblPanelName.Visible = false; } @@ -297,6 +335,7 @@ namespace apprepodbmgr.Eto { canceled = true; Close(); + // throw new NotImplementedException(); } @@ -308,7 +347,8 @@ namespace apprepodbmgr.Eto // Ok... break; case Panels.Strings: - if(minimumPanel == Panels.Strings) return; + if(minimumPanel == Panels.Strings) + return; pnlPanel.Content = panelDescription; currentPanel = Panels.Description; @@ -317,7 +357,8 @@ namespace apprepodbmgr.Eto break; case Panels.Versions: - if(minimumPanel == Panels.Versions) return; + if(minimumPanel == Panels.Versions) + return; pnlPanel.Content = panelStrings; currentPanel = Panels.Strings; @@ -327,7 +368,8 @@ namespace apprepodbmgr.Eto break; } - if(currentPanel != maximumPanel) btnNext.Text = "Next"; + if(currentPanel != maximumPanel) + btnNext.Text = "Next"; } void OnBtnNextClick(object sender, EventArgs eventArgs) @@ -337,7 +379,8 @@ namespace apprepodbmgr.Eto switch(currentPanel) { case Panels.Description: - if(maximumPanel == Panels.Description) return; + if(maximumPanel == Panels.Description) + return; pnlPanel.Content = panelStrings; currentPanel = Panels.Strings; @@ -346,7 +389,8 @@ namespace apprepodbmgr.Eto break; case Panels.Strings: - if(maximumPanel == Panels.Strings) return; + if(maximumPanel == Panels.Strings) + return; pnlPanel.Content = panelVersions; currentPanel = Panels.Versions; @@ -355,7 +399,8 @@ namespace apprepodbmgr.Eto break; case Panels.Versions: - if(minimumPanel == Panels.Versions) return; + if(minimumPanel == Panels.Versions) + return; pnlPanel.Content = panelStrings; currentPanel = Panels.Strings; @@ -365,23 +410,35 @@ namespace apprepodbmgr.Eto break; } - if(currentPanel == maximumPanel) btnNext.Text = "Finish"; + if(currentPanel == maximumPanel) + btnNext.Text = "Finish"; + return; } - if(Context.Readmes?.Count > 0 && !string.IsNullOrWhiteSpace(panelDescription.description)) + if(Context.Readmes?.Count > 0 && + !string.IsNullOrWhiteSpace(panelDescription.description)) description = panelDescription.description; - if(!(Context.Executables?.Count > 0)) return; + if(!(Context.Executables?.Count > 0)) + return; - if(!string.IsNullOrWhiteSpace(panelStrings.txtDeveloper.Text)) developer = panelStrings.txtDeveloper.Text; - if(!string.IsNullOrWhiteSpace(panelStrings.txtPublisher.Text)) publisher = panelStrings.txtPublisher.Text; - if(!string.IsNullOrWhiteSpace(panelStrings.txtProduct.Text)) product = panelStrings.txtProduct.Text; - if(!string.IsNullOrWhiteSpace(panelStrings.txtVersion.Text)) version = panelStrings.txtVersion.Text; + if(!string.IsNullOrWhiteSpace(panelStrings.txtDeveloper.Text)) + developer = panelStrings.txtDeveloper.Text; + + if(!string.IsNullOrWhiteSpace(panelStrings.txtPublisher.Text)) + publisher = panelStrings.txtPublisher.Text; + + if(!string.IsNullOrWhiteSpace(panelStrings.txtProduct.Text)) + product = panelStrings.txtProduct.Text; + + if(!string.IsNullOrWhiteSpace(panelStrings.txtVersion.Text)) + version = panelStrings.txtVersion.Text; foreach(object archsSelectedItem in panelVersions.treeArchs.SelectedItems) { - if(!(archsSelectedItem is string arch)) continue; + if(!(archsSelectedItem is string arch)) + continue; if(Enum.TryParse(arch, true, out ArchitecturesTypeArchitecture realArch)) chosenArchitectures.Add(realArch); @@ -389,12 +446,14 @@ namespace apprepodbmgr.Eto foreach(object osesSelectedItem in panelVersions.treeOs.SelectedItems) { - if(!(osesSelectedItem is TargetOsEntry os)) continue; + if(!(osesSelectedItem is TargetOsEntry os)) + continue; chosenOses.Add(os); } - if(panelVersions.treeVersions.SelectedItem is string chosenVersion) version = chosenVersion; + if(panelVersions.treeVersions.SelectedItem is string chosenVersion) + version = chosenVersion; canceled = false; Close(); @@ -402,9 +461,7 @@ namespace apprepodbmgr.Eto enum Panels { - Description, - Strings, - Versions + Description, Strings, Versions } #region XAML UI elements diff --git a/apprepodbmgr.Eto/dlgMetadata.xeto.cs b/apprepodbmgr.Eto/dlgMetadata.xeto.cs index 4db2ce6..944d8f9 100644 --- a/apprepodbmgr.Eto/dlgMetadata.xeto.cs +++ b/apprepodbmgr.Eto/dlgMetadata.xeto.cs @@ -41,25 +41,25 @@ namespace apprepodbmgr.Eto { public class dlgMetadata : Dialog { - AdvertisementType[] adverts; - AudioMediaType[] audiomedias; - BookType[] books; - LinearMediaType[] linearmedias; - ObservableCollection lstArchitectures; - ObservableCollection lstArchitecturesTypes; - ObservableCollection lstBarcodes; + AdvertisementType[] adverts; + AudioMediaType[] audiomedias; + BookType[] books; + LinearMediaType[] linearmedias; + readonly ObservableCollection lstArchitectures; + readonly ObservableCollection lstArchitecturesTypes; + readonly ObservableCollection lstBarcodes; - ObservableCollection lstBarcodeTypes; - ObservableCollection lstCategories; - ObservableCollection lstDiscs; - ObservableCollection lstDisks; - ObservableCollection lstFilesForMedia; + readonly ObservableCollection lstBarcodeTypes; + readonly ObservableCollection lstCategories; + readonly ObservableCollection lstDiscs; + readonly ObservableCollection lstDisks; + readonly ObservableCollection lstFilesForMedia; - ObservableCollection lstKeywords; - ObservableCollection lstLanguages; - ObservableCollection lstLanguageTypes; - ObservableCollection lstOses; - ObservableCollection lstSubcategories; + readonly ObservableCollection lstKeywords; + readonly ObservableCollection lstLanguages; + readonly ObservableCollection lstLanguageTypes; + readonly ObservableCollection lstOses; + readonly ObservableCollection lstSubcategories; // TODO: Add the options to edit these fields MagazineType[] magazines; @@ -80,7 +80,12 @@ namespace apprepodbmgr.Eto Modified = false; cmbReleaseType = new EnumDropDown(); - stkReleaseType.Items.Add(new StackLayoutItem {Control = cmbReleaseType, Expand = true}); + + stkReleaseType.Items.Add(new StackLayoutItem + { + Control = cmbReleaseType, + Expand = true + }); lstKeywords = new ObservableCollection(); lstBarcodes = new ObservableCollection(); @@ -94,14 +99,22 @@ namespace apprepodbmgr.Eto treeKeywords.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.str)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.str) + }, HeaderText = "Keyword" }); + treeBarcodes.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.code)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.code) + }, HeaderText = "Barcode" }); + treeBarcodes.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -110,44 +123,76 @@ namespace apprepodbmgr.Eto }, HeaderText = "Type" }); + treeCategories.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.str)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.str) + }, HeaderText = "Category" }); + treeSubcategories.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.str)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.str) + }, HeaderText = "Subcategory" }); + treeLanguages.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.str)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.str) + }, HeaderText = "Language" }); + treeOses.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.name)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.name) + }, HeaderText = "Name" }); + treeOses.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.version)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.version) + }, HeaderText = "Version" }); + treeArchitectures.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.str)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.str) + }, HeaderText = "Architecture" }); + treeDiscs.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.path)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.path) + }, HeaderText = "File" }); + treeDisks.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.path)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.path) + }, HeaderText = "File" }); @@ -195,6 +240,7 @@ namespace apprepodbmgr.Eto txtName.ToolTip = "Application name."; txtVersion.ToolTip = "Application version."; txtPartNumber.ToolTip = "Part number of the application distribution."; + txtSerialNumber.ToolTip = "Serial number of the application distribution. Not to be confused with serial number required to install."; } @@ -202,6 +248,7 @@ namespace apprepodbmgr.Eto void FillBarcodeCombo() { lstBarcodeTypes.Clear(); + foreach(BarcodeTypeType type in Enum.GetValues(typeof(BarcodeTypeType))) lstBarcodeTypes.Add(type.ToString()); } @@ -209,6 +256,7 @@ namespace apprepodbmgr.Eto void FillLanguagesCombo() { lstLanguageTypes.Clear(); + foreach(LanguagesTypeLanguage type in Enum.GetValues(typeof(LanguagesTypeLanguage))) lstLanguageTypes.Add(type.ToString()); } @@ -216,44 +264,55 @@ namespace apprepodbmgr.Eto void FillArchitecturesCombo() { lstArchitecturesTypes.Clear(); + foreach(ArchitecturesTypeArchitecture type in Enum.GetValues(typeof(ArchitecturesTypeArchitecture))) lstArchitecturesTypes.Add(type.ToString()); } void FillFilesCombos() { - foreach(KeyValuePair files in Context.Hashes) lstFilesForMedia.Add(files.Key); + foreach(KeyValuePair files in Context.Hashes) + lstFilesForMedia.Add(files.Key); } public void FillFields() { - if(Metadata == null) return; + if(Metadata == null) + return; if(Metadata.Developer != null) foreach(string developer in Metadata.Developer) { - if(!string.IsNullOrWhiteSpace(txtDeveloper.Text)) txtDeveloper.Text += ","; + if(!string.IsNullOrWhiteSpace(txtDeveloper.Text)) + txtDeveloper.Text += ","; + txtDeveloper.Text += developer; } if(Metadata.Publisher != null) foreach(string publisher in Metadata.Publisher) { - if(!string.IsNullOrWhiteSpace(txtPublisher.Text)) txtPublisher.Text += ","; + if(!string.IsNullOrWhiteSpace(txtPublisher.Text)) + txtPublisher.Text += ","; + txtPublisher.Text += publisher; } if(Metadata.Author != null) foreach(string author in Metadata.Author) { - if(!string.IsNullOrWhiteSpace(txtPublisher.Text)) txtPublisher.Text += ","; + if(!string.IsNullOrWhiteSpace(txtPublisher.Text)) + txtPublisher.Text += ","; + txtPublisher.Text += author; } if(Metadata.Performer != null) foreach(string performer in Metadata.Performer) { - if(!string.IsNullOrWhiteSpace(txtPublisher.Text)) txtPublisher.Text += ","; + if(!string.IsNullOrWhiteSpace(txtPublisher.Text)) + txtPublisher.Text += ","; + txtPublisher.Text += performer; } @@ -278,62 +337,131 @@ namespace apprepodbmgr.Eto if(Metadata.Keywords != null) foreach(string keyword in Metadata.Keywords) - lstKeywords.Add(new StringEntry {str = keyword}); + lstKeywords.Add(new StringEntry + { + str = keyword + }); + if(Metadata.Categories != null) foreach(string category in Metadata.Categories) - lstCategories.Add(new StringEntry {str = category}); + lstCategories.Add(new StringEntry + { + str = category + }); + if(Metadata.Subcategories != null) foreach(string subcategory in Metadata.Subcategories) - lstSubcategories.Add(new StringEntry {str = subcategory}); + lstSubcategories.Add(new StringEntry + { + str = subcategory + }); if(Metadata.Languages != null) foreach(LanguagesTypeLanguage language in Metadata.Languages) { - lstLanguages.Add(new StringEntry {str = language.ToString()}); + lstLanguages.Add(new StringEntry + { + str = language.ToString() + }); + lstLanguageTypes.Remove(language.ToString()); } if(Metadata.RequiredOperatingSystems != null) foreach(RequiredOperatingSystemType reqos in Metadata.RequiredOperatingSystems) foreach(string reqver in reqos.Version) - lstOses.Add(new TargetOsEntry {name = reqos.Name, version = reqver}); + lstOses.Add(new TargetOsEntry + { + name = reqos.Name, + version = reqver + }); if(Metadata.Architectures != null) foreach(ArchitecturesTypeArchitecture architecture in Metadata.Architectures) { - lstArchitectures.Add(new StringEntry {str = architecture.ToString()}); + lstArchitectures.Add(new StringEntry + { + str = architecture.ToString() + }); + lstArchitecturesTypes.Remove(architecture.ToString()); } if(Metadata.OpticalDisc != null) foreach(OpticalDiscType disc in Metadata.OpticalDisc) { - lstDiscs.Add(new DiscEntry {path = disc.Image.Value, disc = disc}); - List files = new List {disc.Image.Value}; - if(disc.ADIP != null) files.Add(disc.ADIP.Image); - if(disc.ATIP != null) files.Add(disc.ATIP.Image); - if(disc.BCA != null) files.Add(disc.BCA.Image); - if(disc.CMI != null) files.Add(disc.CMI.Image); - if(disc.DCB != null) files.Add(disc.DCB.Image); - if(disc.DDS != null) files.Add(disc.DDS.Image); - if(disc.DMI != null) files.Add(disc.DMI.Image); - if(disc.LastRMD != null) files.Add(disc.LastRMD.Image); + lstDiscs.Add(new DiscEntry + { + path = disc.Image.Value, + disc = disc + }); + + List files = new List + { + disc.Image.Value + }; + + if(disc.ADIP != null) + files.Add(disc.ADIP.Image); + + if(disc.ATIP != null) + files.Add(disc.ATIP.Image); + + if(disc.BCA != null) + files.Add(disc.BCA.Image); + + if(disc.CMI != null) + files.Add(disc.CMI.Image); + + if(disc.DCB != null) + files.Add(disc.DCB.Image); + + if(disc.DDS != null) + files.Add(disc.DDS.Image); + + if(disc.DMI != null) + files.Add(disc.DMI.Image); + + if(disc.LastRMD != null) + files.Add(disc.LastRMD.Image); + if(disc.LeadIn != null) foreach(BorderType border in disc.LeadIn) files.Add(border.Image); - if(disc.LeadInCdText != null) files.Add(disc.LeadInCdText.Image); + + if(disc.LeadInCdText != null) + files.Add(disc.LeadInCdText.Image); + if(disc.LeadOut != null) foreach(BorderType border in disc.LeadOut) files.Add(border.Image); - if(disc.MediaID != null) files.Add(disc.MediaID.Image); - if(disc.PAC != null) files.Add(disc.PAC.Image); - if(disc.PFI != null) files.Add(disc.PFI.Image); - if(disc.PFIR != null) files.Add(disc.PFIR.Image); - if(disc.PMA != null) files.Add(disc.PMA.Image); - if(disc.PRI != null) files.Add(disc.PRI.Image); - if(disc.SAI != null) files.Add(disc.SAI.Image); - if(disc.TOC != null) files.Add(disc.TOC.Image); - if(disc.Track != null) files.AddRange(disc.Track.Select(track => track.Image.Value)); + + if(disc.MediaID != null) + files.Add(disc.MediaID.Image); + + if(disc.PAC != null) + files.Add(disc.PAC.Image); + + if(disc.PFI != null) + files.Add(disc.PFI.Image); + + if(disc.PFIR != null) + files.Add(disc.PFIR.Image); + + if(disc.PMA != null) + files.Add(disc.PMA.Image); + + if(disc.PRI != null) + files.Add(disc.PRI.Image); + + if(disc.SAI != null) + files.Add(disc.SAI.Image); + + if(disc.TOC != null) + files.Add(disc.TOC.Image); + + if(disc.Track != null) + files.AddRange(disc.Track.Select(track => track.Image.Value)); foreach(string file in files) if(lstFilesForMedia.Contains(file)) @@ -343,32 +471,67 @@ namespace apprepodbmgr.Eto if(Metadata.BlockMedia != null) foreach(BlockMediaType disk in Metadata.BlockMedia) { - lstDisks.Add(new DiskEntry {path = disk.Image.Value, disk = disk}); - List files = new List {disk.Image.Value}; - if(disk.ATA?.Identify != null) files.Add(disk.ATA.Identify.Image); - if(disk.MAM != null) files.Add(disk.MAM.Image); - if(disk.PCI?.ExpansionROM != null) files.Add(disk.PCI.ExpansionROM.Image.Value); - if(disk.PCMCIA?.CIS != null) files.Add(disk.PCMCIA.CIS.Image); + lstDisks.Add(new DiskEntry + { + path = disk.Image.Value, + disk = disk + }); + + List files = new List + { + disk.Image.Value + }; + + if(disk.ATA?.Identify != null) + files.Add(disk.ATA.Identify.Image); + + if(disk.MAM != null) + files.Add(disk.MAM.Image); + + if(disk.PCI?.ExpansionROM != null) + files.Add(disk.PCI.ExpansionROM.Image.Value); + + if(disk.PCMCIA?.CIS != null) + files.Add(disk.PCMCIA.CIS.Image); + if(disk.SCSI != null) { - if(disk.SCSI.Inquiry != null) files.Add(disk.SCSI.Inquiry.Image); - if(disk.SCSI.LogSense != null) files.Add(disk.SCSI.LogSense.Image); - if(disk.SCSI.ModeSense != null) files.Add(disk.SCSI.ModeSense.Image); - if(disk.SCSI.ModeSense10 != null) files.Add(disk.SCSI.ModeSense10.Image); - if(disk.SCSI.EVPD != null) files.AddRange(disk.SCSI.EVPD.Select(evpd => evpd.Image)); + if(disk.SCSI.Inquiry != null) + files.Add(disk.SCSI.Inquiry.Image); + + if(disk.SCSI.LogSense != null) + files.Add(disk.SCSI.LogSense.Image); + + if(disk.SCSI.ModeSense != null) + files.Add(disk.SCSI.ModeSense.Image); + + if(disk.SCSI.ModeSense10 != null) + files.Add(disk.SCSI.ModeSense10.Image); + + if(disk.SCSI.EVPD != null) + files.AddRange(disk.SCSI.EVPD.Select(evpd => evpd.Image)); } if(disk.SecureDigital != null) { - if(disk.SecureDigital.CID != null) files.Add(disk.SecureDigital.CID.Image); - if(disk.SecureDigital.CSD != null) files.Add(disk.SecureDigital.CSD.Image); - if(disk.MultiMediaCard.ExtendedCSD != null) files.Add(disk.MultiMediaCard.ExtendedCSD.Image); + if(disk.SecureDigital.CID != null) + files.Add(disk.SecureDigital.CID.Image); + + if(disk.SecureDigital.CSD != null) + files.Add(disk.SecureDigital.CSD.Image); + + if(disk.MultiMediaCard.ExtendedCSD != null) + files.Add(disk.MultiMediaCard.ExtendedCSD.Image); } if(disk.TapeInformation != null) files.AddRange(disk.TapeInformation.Select(tapePart => tapePart.Image.Value)); - if(disk.Track != null) files.AddRange(disk.Track.Select(track => track.Image.Value)); - if(disk.USB?.Descriptors != null) files.Add(disk.USB.Descriptors.Image); + + if(disk.Track != null) + files.AddRange(disk.Track.Select(track => track.Image.Value)); + + if(disk.USB?.Descriptors != null) + files.Add(disk.USB.Descriptors.Image); foreach(string file in files) if(lstFilesForMedia.Contains(file)) @@ -384,63 +547,69 @@ namespace apprepodbmgr.Eto audiomedias = Metadata.AudioMedia; } - protected void OnChkKnownReleaseTypeToggled(object sender, EventArgs e) - { + protected void OnChkKnownReleaseTypeToggled(object sender, EventArgs e) => cmbReleaseType.Enabled = chkKnownReleaseType.Checked.Value; - } - protected void OnChkReleaseDateToggled(object sender, EventArgs e) - { + protected void OnChkReleaseDateToggled(object sender, EventArgs e) => cldReleaseDate.Enabled = !chkReleaseDate.Checked.Value; - } protected void OnBtnAddKeywordClicked(object sender, EventArgs e) { - lstKeywords.Add(new StringEntry {str = txtNewKeyword.Text}); + lstKeywords.Add(new StringEntry + { + str = txtNewKeyword.Text + }); + txtNewKeyword.Text = ""; } protected void OnBtnRemoveKeywordClicked(object sender, EventArgs e) { - if(treeKeywords.SelectedItem != null) lstKeywords.Remove((StringEntry)treeKeywords.SelectedItem); + if(treeKeywords.SelectedItem != null) + lstKeywords.Remove((StringEntry)treeKeywords.SelectedItem); } - protected void OnBtnClearKeywordsClicked(object sender, EventArgs e) - { - lstKeywords.Clear(); - } + protected void OnBtnClearKeywordsClicked(object sender, EventArgs e) => lstKeywords.Clear(); protected void OnBtnAddBarcodeClicked(object sender, EventArgs e) { - if(string.IsNullOrEmpty(cmbBarcodes.Text)) return; + if(string.IsNullOrEmpty(cmbBarcodes.Text)) + return; lstBarcodes.Add(new BarcodeEntry { code = txtNewBarcode.Text, type = (BarcodeTypeType)Enum.Parse(typeof(BarcodeTypeType), cmbBarcodes.Text) }); + txtNewBarcode.Text = ""; } - protected void OnBtnClearBarcodesClicked(object sender, EventArgs e) - { - lstBarcodes.Clear(); - } + protected void OnBtnClearBarcodesClicked(object sender, EventArgs e) => lstBarcodes.Clear(); protected void OnBtnRemoveBarcodeClicked(object sender, EventArgs e) { - if(treeBarcodes.SelectedItem != null) lstBarcodes.Remove((BarcodeEntry)treeBarcodes.SelectedItem); + if(treeBarcodes.SelectedItem != null) + lstBarcodes.Remove((BarcodeEntry)treeBarcodes.SelectedItem); } protected void OnBtnAddCategoryClicked(object sender, EventArgs e) { - lstCategories.Add(new StringEntry {str = txtNewCategory.Text}); + lstCategories.Add(new StringEntry + { + str = txtNewCategory.Text + }); + txtNewCategory.Text = ""; } protected void OnBtnAddSubcategoryClicked(object sender, EventArgs e) { - lstSubcategories.Add(new StringEntry {str = txtNewSubcategory.Text}); + lstSubcategories.Add(new StringEntry + { + str = txtNewSubcategory.Text + }); + txtNewSubcategory.Text = ""; } @@ -450,32 +619,33 @@ namespace apprepodbmgr.Eto lstSubcategories.Remove((StringEntry)treeSubcategories.SelectedItem); } - protected void OnBtnClearSubcategoriesClicked(object sender, EventArgs e) - { - lstSubcategories.Clear(); - } + protected void OnBtnClearSubcategoriesClicked(object sender, EventArgs e) => lstSubcategories.Clear(); protected void OnBtnRemoveCategoryClicked(object sender, EventArgs e) { - if(treeCategories.SelectedItem != null) lstCategories.Remove((StringEntry)treeCategories.SelectedItem); + if(treeCategories.SelectedItem != null) + lstCategories.Remove((StringEntry)treeCategories.SelectedItem); } - protected void OnBtnClearCategoriesClicked(object sender, EventArgs e) - { - lstCategories.Clear(); - } + protected void OnBtnClearCategoriesClicked(object sender, EventArgs e) => lstCategories.Clear(); protected void OnBtnAddLanguageClicked(object sender, EventArgs e) { - if(string.IsNullOrWhiteSpace(cmbLanguages.Text)) return; + if(string.IsNullOrWhiteSpace(cmbLanguages.Text)) + return; + + lstLanguages.Add(new StringEntry + { + str = cmbLanguages.Text + }); - lstLanguages.Add(new StringEntry {str = cmbLanguages.Text}); lstLanguageTypes.Remove(cmbLanguages.Text); } protected void OnBtnRemoveLanguageClicked(object sender, EventArgs e) { - if(treeLanguages.SelectedItem == null) return; + if(treeLanguages.SelectedItem == null) + return; lstLanguageTypes.Add(((StringEntry)treeLanguages.SelectedItem).str); lstLanguages.Remove((StringEntry)treeLanguages.SelectedItem); @@ -492,35 +662,45 @@ namespace apprepodbmgr.Eto if(string.IsNullOrWhiteSpace(txtNewOsName.Text)) { MessageBox.Show("Operating system name cannot be empty.", MessageBoxType.Error); + return; } if(string.IsNullOrWhiteSpace(txtNewOsVersion.Text)) { MessageBox.Show("Operating system version cannot be empty.", MessageBoxType.Error); + return; } - lstOses.Add(new TargetOsEntry {name = txtNewOsName.Text, version = txtNewOsVersion.Text}); + lstOses.Add(new TargetOsEntry + { + name = txtNewOsName.Text, + version = txtNewOsVersion.Text + }); + txtNewOsName.Text = ""; txtNewOsVersion.Text = ""; } - protected void OnBtnClearOsesClicked(object sender, EventArgs e) - { - lstOses.Clear(); - } + protected void OnBtnClearOsesClicked(object sender, EventArgs e) => lstOses.Clear(); protected void OnBtnRemoveOsClicked(object sender, EventArgs e) { - if(treeOses.SelectedItem != null) lstOses.Remove((TargetOsEntry)treeOses.SelectedItem); + if(treeOses.SelectedItem != null) + lstOses.Remove((TargetOsEntry)treeOses.SelectedItem); } protected void OnBtnAddArchitectureClicked(object sender, EventArgs e) { - if(string.IsNullOrWhiteSpace(cmbArchitectures.Text)) return; + if(string.IsNullOrWhiteSpace(cmbArchitectures.Text)) + return; + + lstArchitectures.Add(new StringEntry + { + str = cmbArchitectures.Text + }); - lstArchitectures.Add(new StringEntry {str = cmbArchitectures.Text}); lstArchitecturesTypes.Remove(cmbArchitectures.Text); } @@ -532,7 +712,8 @@ namespace apprepodbmgr.Eto protected void OnBtnRemoveArchitectureClicked(object sender, EventArgs e) { - if(treeArchitectures.SelectedItem == null) return; + if(treeArchitectures.SelectedItem == null) + return; lstArchitecturesTypes.Add(((StringEntry)treeArchitectures.SelectedItem).str); lstArchitectures.Remove((StringEntry)treeArchitectures.SelectedItem); @@ -576,14 +757,16 @@ namespace apprepodbmgr.Eto OnDiscAddFailed(null); } - void UpdateDiscProgress1(string text, string inner, long current, long maximum) - { + void UpdateDiscProgress1(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { lblAddDisc1.Text = !string.IsNullOrWhiteSpace(inner) ? inner : text; + if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -595,18 +778,20 @@ namespace apprepodbmgr.Eto prgAddDisc1.MaxValue = (int)maximum; prgAddDisc1.Value = (int)current; } - else prgAddDisc1.Indeterminate = true; + else + prgAddDisc1.Indeterminate = true; }); - } - void UpdateDiscProgress2(string text, string inner, long current, long maximum) - { + void UpdateDiscProgress2(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { lblAddDisc2.Text = !string.IsNullOrWhiteSpace(inner) ? inner : text; + if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -618,116 +803,164 @@ namespace apprepodbmgr.Eto prgAddDisc2.MaxValue = (int)maximum; prgAddDisc2.Value = (int)current; } - else prgAddDisc2.Indeterminate = true; + else + prgAddDisc2.Indeterminate = true; }); - } - void OnDiscAddFailed(string text) + void OnDiscAddFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(!stopped) MessageBox.Show(text, MessageBoxType.Error); - Context.SelectedFile = ""; - tabGeneral.Visible = true; - tabKeywords.Visible = true; - tabBarcodes.Visible = true; - tabCategories.Visible = true; - tabLanguages.Visible = true; - tabTargetOs.Visible = true; - tabArchitectures.Visible = true; - tabDisks.Visible = true; - prgAddDisc1.Visible = false; - prgAddDisc2.Visible = false; - lblAddDisc1.Visible = false; - lblAddDisc2.Visible = false; - btnCancel.Visible = true; - btnOK.Visible = true; - btnEditDisc.Visible = true; - btnClearDiscs.Visible = true; - Workers.Failed -= OnDiscAddFailed; - Workers.Finished -= OnDiscAddFinished; - Workers.UpdateProgress -= UpdateDiscProgress1; - Workers.UpdateProgress2 -= UpdateDiscProgress2; - Context.WorkingDisc = null; - btnStopAddDisc.Visible = false; - btnAddDisc.Visible = true; - btnRemoveDisc.Visible = true; - thdDisc = null; - }); - } + if(!stopped) + MessageBox.Show(text, MessageBoxType.Error); - void OnDiscAddFinished() + Context.SelectedFile = ""; + tabGeneral.Visible = true; + tabKeywords.Visible = true; + tabBarcodes.Visible = true; + tabCategories.Visible = true; + tabLanguages.Visible = true; + tabTargetOs.Visible = true; + tabArchitectures.Visible = true; + tabDisks.Visible = true; + prgAddDisc1.Visible = false; + prgAddDisc2.Visible = false; + lblAddDisc1.Visible = false; + lblAddDisc2.Visible = false; + btnCancel.Visible = true; + btnOK.Visible = true; + btnEditDisc.Visible = true; + btnClearDiscs.Visible = true; + Workers.Failed -= OnDiscAddFailed; + Workers.Finished -= OnDiscAddFinished; + Workers.UpdateProgress -= UpdateDiscProgress1; + Workers.UpdateProgress2 -= UpdateDiscProgress2; + Context.WorkingDisc = null; + btnStopAddDisc.Visible = false; + btnAddDisc.Visible = true; + btnRemoveDisc.Visible = true; + thdDisc = null; + }); + + void OnDiscAddFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + if(Context.WorkingDisc == null) + return; + + OpticalDiscType disc = Context.WorkingDisc; + + lstDiscs.Add(new DiscEntry { - if(Context.WorkingDisc == null) return; - - OpticalDiscType disc = Context.WorkingDisc; - - lstDiscs.Add(new DiscEntry {path = Context.SelectedFile, disc = disc}); - List files = new List {disc.Image.Value}; - if(disc.ADIP != null) files.Add(disc.ADIP.Image); - if(disc.ATIP != null) files.Add(disc.ATIP.Image); - if(disc.BCA != null) files.Add(disc.BCA.Image); - if(disc.CMI != null) files.Add(disc.CMI.Image); - if(disc.DCB != null) files.Add(disc.DCB.Image); - if(disc.DDS != null) files.Add(disc.DDS.Image); - if(disc.DMI != null) files.Add(disc.DMI.Image); - if(disc.LastRMD != null) files.Add(disc.LastRMD.Image); - if(disc.LeadIn != null) files.AddRange(disc.LeadIn.Select(border => border.Image)); - if(disc.LeadInCdText != null) files.Add(disc.LeadInCdText.Image); - if(disc.LeadOut != null) files.AddRange(disc.LeadOut.Select(border => border.Image)); - if(disc.MediaID != null) files.Add(disc.MediaID.Image); - if(disc.PAC != null) files.Add(disc.PAC.Image); - if(disc.PFI != null) files.Add(disc.PFI.Image); - if(disc.PFIR != null) files.Add(disc.PFIR.Image); - if(disc.PMA != null) files.Add(disc.PMA.Image); - if(disc.PRI != null) files.Add(disc.PRI.Image); - if(disc.SAI != null) files.Add(disc.SAI.Image); - if(disc.TOC != null) files.Add(disc.TOC.Image); - if(disc.Track != null) files.AddRange(disc.Track.Select(track => track.Image.Value)); - - foreach(string file in files) lstFilesForMedia.Remove(file); - - Context.SelectedFile = ""; - tabGeneral.Visible = true; - tabKeywords.Visible = true; - tabBarcodes.Visible = true; - tabCategories.Visible = true; - tabLanguages.Visible = true; - tabTargetOs.Visible = true; - tabArchitectures.Visible = true; - tabDisks.Visible = true; - prgAddDisc1.Visible = false; - prgAddDisc2.Visible = false; - lblAddDisc1.Visible = false; - lblAddDisc2.Visible = false; - btnCancel.Visible = true; - btnOK.Visible = true; - btnEditDisc.Visible = true; - btnClearDiscs.Visible = true; - Workers.Failed -= OnDiscAddFailed; - Workers.Finished -= OnDiscAddFinished; - Workers.UpdateProgress -= UpdateDiscProgress1; - Workers.UpdateProgress2 -= UpdateDiscProgress2; - Context.WorkingDisc = null; - btnStopAddDisc.Visible = false; - btnAddDisc.Visible = true; - btnRemoveDisc.Visible = true; - thdDisc = null; + path = Context.SelectedFile, + disc = disc }); - } + + List files = new List + { + disc.Image.Value + }; + + if(disc.ADIP != null) + files.Add(disc.ADIP.Image); + + if(disc.ATIP != null) + files.Add(disc.ATIP.Image); + + if(disc.BCA != null) + files.Add(disc.BCA.Image); + + if(disc.CMI != null) + files.Add(disc.CMI.Image); + + if(disc.DCB != null) + files.Add(disc.DCB.Image); + + if(disc.DDS != null) + files.Add(disc.DDS.Image); + + if(disc.DMI != null) + files.Add(disc.DMI.Image); + + if(disc.LastRMD != null) + files.Add(disc.LastRMD.Image); + + if(disc.LeadIn != null) + files.AddRange(disc.LeadIn.Select(border => border.Image)); + + if(disc.LeadInCdText != null) + files.Add(disc.LeadInCdText.Image); + + if(disc.LeadOut != null) + files.AddRange(disc.LeadOut.Select(border => border.Image)); + + if(disc.MediaID != null) + files.Add(disc.MediaID.Image); + + if(disc.PAC != null) + files.Add(disc.PAC.Image); + + if(disc.PFI != null) + files.Add(disc.PFI.Image); + + if(disc.PFIR != null) + files.Add(disc.PFIR.Image); + + if(disc.PMA != null) + files.Add(disc.PMA.Image); + + if(disc.PRI != null) + files.Add(disc.PRI.Image); + + if(disc.SAI != null) + files.Add(disc.SAI.Image); + + if(disc.TOC != null) + files.Add(disc.TOC.Image); + + if(disc.Track != null) + files.AddRange(disc.Track.Select(track => track.Image.Value)); + + foreach(string file in files) + lstFilesForMedia.Remove(file); + + Context.SelectedFile = ""; + tabGeneral.Visible = true; + tabKeywords.Visible = true; + tabBarcodes.Visible = true; + tabCategories.Visible = true; + tabLanguages.Visible = true; + tabTargetOs.Visible = true; + tabArchitectures.Visible = true; + tabDisks.Visible = true; + prgAddDisc1.Visible = false; + prgAddDisc2.Visible = false; + lblAddDisc1.Visible = false; + lblAddDisc2.Visible = false; + btnCancel.Visible = true; + btnOK.Visible = true; + btnEditDisc.Visible = true; + btnClearDiscs.Visible = true; + Workers.Failed -= OnDiscAddFailed; + Workers.Finished -= OnDiscAddFinished; + Workers.UpdateProgress -= UpdateDiscProgress1; + Workers.UpdateProgress2 -= UpdateDiscProgress2; + Context.WorkingDisc = null; + btnStopAddDisc.Visible = false; + btnAddDisc.Visible = true; + btnRemoveDisc.Visible = true; + thdDisc = null; + }); protected void OnBtnClearDiscsClicked(object sender, EventArgs e) { lstDiscs.Clear(); + // TODO: Don't add files that are in disks FillFilesCombos(); } protected void OnBtnRemoveDiscClicked(object sender, EventArgs e) { - if(treeDiscs.SelectedItem == null) return; + if(treeDiscs.SelectedItem == null) + return; lstFilesForMedia.Add(((DiscEntry)treeDiscs.SelectedItem).path); lstDiscs.Remove((DiscEntry)treeDiscs.SelectedItem); @@ -771,14 +1004,16 @@ namespace apprepodbmgr.Eto OnDiskAddFailed(null); } - void UpdateDiskProgress1(string text, string inner, long current, long maximum) - { + void UpdateDiskProgress1(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { lblAddDisk1.Text = !string.IsNullOrWhiteSpace(inner) ? inner : text; + if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -790,18 +1025,20 @@ namespace apprepodbmgr.Eto prgAddDisk1.MaxValue = (int)maximum; prgAddDisk1.Value = (int)current; } - else prgAddDisk1.Indeterminate = true; + else + prgAddDisk1.Indeterminate = true; }); - } - void UpdateDiskProgress2(string text, string inner, long current, long maximum) - { + void UpdateDiskProgress2(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { lblAddDisk2.Text = !string.IsNullOrWhiteSpace(inner) ? inner : text; + if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -813,120 +1050,155 @@ namespace apprepodbmgr.Eto prgAddDisk2.MaxValue = (int)maximum; prgAddDisk2.Value = (int)current; } - else prgAddDisk2.Indeterminate = true; + else + prgAddDisk2.Indeterminate = true; }); - } - void OnDiskAddFailed(string text) + void OnDiskAddFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(!stopped) MessageBox.Show(text, MessageBoxType.Error); - Context.SelectedFile = ""; - tabGeneral.Visible = true; - tabKeywords.Visible = true; - tabBarcodes.Visible = true; - tabCategories.Visible = true; - tabLanguages.Visible = true; - tabTargetOs.Visible = true; - tabArchitectures.Visible = true; - tabDiscs.Visible = true; - prgAddDisk1.Visible = false; - prgAddDisk2.Visible = false; - lblAddDisk1.Visible = false; - lblAddDisk2.Visible = false; - btnCancel.Visible = true; - btnOK.Visible = true; - btnEditDisk.Visible = true; - btnClearDisks.Visible = true; - Workers.Failed -= OnDiskAddFailed; - Workers.Finished -= OnDiskAddFinished; - Workers.UpdateProgress -= UpdateDiskProgress1; - Workers.UpdateProgress2 -= UpdateDiskProgress2; - Context.WorkingDisk = null; - btnStopAddDisk.Visible = false; - btnAddDisk.Visible = true; - btnRemoveDisk.Visible = true; - thdDisk = null; - }); - } + if(!stopped) + MessageBox.Show(text, MessageBoxType.Error); - void OnDiskAddFinished() + Context.SelectedFile = ""; + tabGeneral.Visible = true; + tabKeywords.Visible = true; + tabBarcodes.Visible = true; + tabCategories.Visible = true; + tabLanguages.Visible = true; + tabTargetOs.Visible = true; + tabArchitectures.Visible = true; + tabDiscs.Visible = true; + prgAddDisk1.Visible = false; + prgAddDisk2.Visible = false; + lblAddDisk1.Visible = false; + lblAddDisk2.Visible = false; + btnCancel.Visible = true; + btnOK.Visible = true; + btnEditDisk.Visible = true; + btnClearDisks.Visible = true; + Workers.Failed -= OnDiskAddFailed; + Workers.Finished -= OnDiskAddFinished; + Workers.UpdateProgress -= UpdateDiskProgress1; + Workers.UpdateProgress2 -= UpdateDiskProgress2; + Context.WorkingDisk = null; + btnStopAddDisk.Visible = false; + btnAddDisk.Visible = true; + btnRemoveDisk.Visible = true; + thdDisk = null; + }); + + void OnDiskAddFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + if(Context.WorkingDisk == null) + return; + + BlockMediaType disk = Context.WorkingDisk; + + lstDisks.Add(new DiskEntry { - if(Context.WorkingDisk == null) return; - - BlockMediaType disk = Context.WorkingDisk; - - lstDisks.Add(new DiskEntry {path = disk.Image.Value, disk = disk}); - List files = new List {disk.Image.Value}; - if(disk.ATA?.Identify != null) files.Add(disk.ATA.Identify.Image); - if(disk.MAM != null) files.Add(disk.MAM.Image); - if(disk.PCI?.ExpansionROM != null) files.Add(disk.PCI.ExpansionROM.Image.Value); - if(disk.PCMCIA?.CIS != null) files.Add(disk.PCMCIA.CIS.Image); - if(disk.SCSI != null) - { - if(disk.SCSI.Inquiry != null) files.Add(disk.SCSI.Inquiry.Image); - if(disk.SCSI.LogSense != null) files.Add(disk.SCSI.LogSense.Image); - if(disk.SCSI.ModeSense != null) files.Add(disk.SCSI.ModeSense.Image); - if(disk.SCSI.ModeSense10 != null) files.Add(disk.SCSI.ModeSense10.Image); - if(disk.SCSI.EVPD != null) files.AddRange(disk.SCSI.EVPD.Select(evpd => evpd.Image)); - } - - if(disk.SecureDigital != null) - { - if(disk.SecureDigital.CID != null) files.Add(disk.SecureDigital.CID.Image); - if(disk.SecureDigital.CSD != null) files.Add(disk.SecureDigital.CSD.Image); - if(disk.MultiMediaCard.ExtendedCSD != null) files.Add(disk.MultiMediaCard.ExtendedCSD.Image); - } - - if(disk.TapeInformation != null) - files.AddRange(disk.TapeInformation.Select(tapePart => tapePart.Image.Value)); - if(disk.Track != null) files.AddRange(disk.Track.Select(track => track.Image.Value)); - if(disk.USB?.Descriptors != null) files.Add(disk.USB.Descriptors.Image); - - foreach(string file in files) lstFilesForMedia.Remove(file); - - Context.SelectedFile = ""; - tabGeneral.Visible = true; - tabKeywords.Visible = true; - tabBarcodes.Visible = true; - tabCategories.Visible = true; - tabLanguages.Visible = true; - tabTargetOs.Visible = true; - tabArchitectures.Visible = true; - tabDiscs.Visible = true; - prgAddDisk1.Visible = false; - prgAddDisk2.Visible = false; - lblAddDisk1.Visible = false; - lblAddDisk2.Visible = false; - btnCancel.Visible = true; - btnOK.Visible = true; - btnEditDisk.Visible = true; - btnClearDisks.Visible = true; - Workers.Failed -= OnDiskAddFailed; - Workers.Finished -= OnDiskAddFinished; - Workers.UpdateProgress -= UpdateDiskProgress1; - Workers.UpdateProgress2 -= UpdateDiskProgress2; - Context.WorkingDisk = null; - btnStopAddDisk.Visible = false; - btnAddDisk.Visible = true; - btnRemoveDisk.Visible = true; - thdDisk = null; + path = disk.Image.Value, + disk = disk }); - } + + List files = new List + { + disk.Image.Value + }; + + if(disk.ATA?.Identify != null) + files.Add(disk.ATA.Identify.Image); + + if(disk.MAM != null) + files.Add(disk.MAM.Image); + + if(disk.PCI?.ExpansionROM != null) + files.Add(disk.PCI.ExpansionROM.Image.Value); + + if(disk.PCMCIA?.CIS != null) + files.Add(disk.PCMCIA.CIS.Image); + + if(disk.SCSI != null) + { + if(disk.SCSI.Inquiry != null) + files.Add(disk.SCSI.Inquiry.Image); + + if(disk.SCSI.LogSense != null) + files.Add(disk.SCSI.LogSense.Image); + + if(disk.SCSI.ModeSense != null) + files.Add(disk.SCSI.ModeSense.Image); + + if(disk.SCSI.ModeSense10 != null) + files.Add(disk.SCSI.ModeSense10.Image); + + if(disk.SCSI.EVPD != null) + files.AddRange(disk.SCSI.EVPD.Select(evpd => evpd.Image)); + } + + if(disk.SecureDigital != null) + { + if(disk.SecureDigital.CID != null) + files.Add(disk.SecureDigital.CID.Image); + + if(disk.SecureDigital.CSD != null) + files.Add(disk.SecureDigital.CSD.Image); + + if(disk.MultiMediaCard.ExtendedCSD != null) + files.Add(disk.MultiMediaCard.ExtendedCSD.Image); + } + + if(disk.TapeInformation != null) + files.AddRange(disk.TapeInformation.Select(tapePart => tapePart.Image.Value)); + + if(disk.Track != null) + files.AddRange(disk.Track.Select(track => track.Image.Value)); + + if(disk.USB?.Descriptors != null) + files.Add(disk.USB.Descriptors.Image); + + foreach(string file in files) + lstFilesForMedia.Remove(file); + + Context.SelectedFile = ""; + tabGeneral.Visible = true; + tabKeywords.Visible = true; + tabBarcodes.Visible = true; + tabCategories.Visible = true; + tabLanguages.Visible = true; + tabTargetOs.Visible = true; + tabArchitectures.Visible = true; + tabDiscs.Visible = true; + prgAddDisk1.Visible = false; + prgAddDisk2.Visible = false; + lblAddDisk1.Visible = false; + lblAddDisk2.Visible = false; + btnCancel.Visible = true; + btnOK.Visible = true; + btnEditDisk.Visible = true; + btnClearDisks.Visible = true; + Workers.Failed -= OnDiskAddFailed; + Workers.Finished -= OnDiskAddFinished; + Workers.UpdateProgress -= UpdateDiskProgress1; + Workers.UpdateProgress2 -= UpdateDiskProgress2; + Context.WorkingDisk = null; + btnStopAddDisk.Visible = false; + btnAddDisk.Visible = true; + btnRemoveDisk.Visible = true; + thdDisk = null; + }); protected void OnBtnClearDisksClicked(object sender, EventArgs e) { lstDisks.Clear(); + // TODO: Don't add files that are discs FillFilesCombos(); } protected void OnBtnRemoveDiskClicked(object sender, EventArgs e) { - if(treeDisks.SelectedItem == null) return; + if(treeDisks.SelectedItem == null) + return; lstFilesForMedia.Add(((DiskEntry)treeDisks.SelectedItem).path); lstDisks.Remove((DiskEntry)treeDisks.SelectedItem); @@ -951,14 +1223,30 @@ namespace apprepodbmgr.Eto List subcategories = new List(); List systems = new List(); - if(!string.IsNullOrEmpty(txtAuthor.Text)) Metadata.Author = txtAuthor.Text.Split(','); - if(!string.IsNullOrEmpty(txtDeveloper.Text)) Metadata.Developer = txtDeveloper.Text.Split(','); - if(!string.IsNullOrEmpty(txtName.Text)) Metadata.Name = txtName.Text; - if(!string.IsNullOrEmpty(txtPartNumber.Text)) Metadata.PartNumber = txtPartNumber.Text; - if(!string.IsNullOrEmpty(txtPerformer.Text)) Metadata.Performer = txtPerformer.Text.Split(','); - if(!string.IsNullOrEmpty(txtPublisher.Text)) Metadata.Publisher = txtPublisher.Text.Split(','); - if(!string.IsNullOrEmpty(txtSerialNumber.Text)) Metadata.SerialNumber = txtSerialNumber.Text; - if(!string.IsNullOrEmpty(txtVersion.Text)) Metadata.Version = txtVersion.Text; + if(!string.IsNullOrEmpty(txtAuthor.Text)) + Metadata.Author = txtAuthor.Text.Split(','); + + if(!string.IsNullOrEmpty(txtDeveloper.Text)) + Metadata.Developer = txtDeveloper.Text.Split(','); + + if(!string.IsNullOrEmpty(txtName.Text)) + Metadata.Name = txtName.Text; + + if(!string.IsNullOrEmpty(txtPartNumber.Text)) + Metadata.PartNumber = txtPartNumber.Text; + + if(!string.IsNullOrEmpty(txtPerformer.Text)) + Metadata.Performer = txtPerformer.Text.Split(','); + + if(!string.IsNullOrEmpty(txtPublisher.Text)) + Metadata.Publisher = txtPublisher.Text.Split(','); + + if(!string.IsNullOrEmpty(txtSerialNumber.Text)) + Metadata.SerialNumber = txtSerialNumber.Text; + + if(!string.IsNullOrEmpty(txtVersion.Text)) + Metadata.Version = txtVersion.Text; + if(!chkReleaseDate.Checked.Value) { Metadata.ReleaseDate = cldReleaseDate.Value.Value; @@ -977,33 +1265,46 @@ namespace apprepodbmgr.Eto foreach(BarcodeEntry entry in lstBarcodes) { - BarcodeType barcode = new BarcodeType {type = entry.type, Value = entry.code}; + var barcode = new BarcodeType + { + type = entry.type, + Value = entry.code + }; + barcodes.Add(barcode); } - foreach(DiskEntry entry in lstDisks) disks.Add(entry.disk); + foreach(DiskEntry entry in lstDisks) + disks.Add(entry.disk); - foreach(StringEntry entry in lstCategories) categories.Add(entry.str); + foreach(StringEntry entry in lstCategories) + categories.Add(entry.str); - foreach(StringEntry entry in lstKeywords) keywords.Add(entry.str); + foreach(StringEntry entry in lstKeywords) + keywords.Add(entry.str); foreach(StringEntry entry in lstLanguages) languages.Add((LanguagesTypeLanguage)Enum.Parse(typeof(LanguagesTypeLanguage), entry.str)); - foreach(DiscEntry entry in lstDiscs) discs.Add(entry.disc); + foreach(DiscEntry entry in lstDiscs) + discs.Add(entry.disc); - foreach(StringEntry entry in lstSubcategories) subcategories.Add(entry.str); + foreach(StringEntry entry in lstSubcategories) + subcategories.Add(entry.str); if(lstOses.Count > 0) { Dictionary> osesDict = new Dictionary>(); + foreach(TargetOsEntry entry in lstOses.OrderBy(t => t.name).ThenBy(t => t.version)) { osesDict.TryGetValue(entry.name, out List versList); - if(versList == null) versList = new List(); + if(versList == null) + versList = new List(); - if(versList.Contains(entry.version)) continue; + if(versList.Contains(entry.version)) + continue; versList.Add(entry.version); versList.Sort(); @@ -1011,24 +1312,40 @@ namespace apprepodbmgr.Eto osesDict.Add(entry.name, versList); } - Metadata.RequiredOperatingSystems = osesDict - .OrderBy(t => t.Key) - .Select(entry => new RequiredOperatingSystemType - { - Name = entry.Key, - Version = entry.Value.ToArray() - }).ToArray(); + Metadata.RequiredOperatingSystems = osesDict.OrderBy(t => t.Key). + Select(entry => new RequiredOperatingSystemType + { + Name = entry.Key, + Version = entry.Value.ToArray() + }).ToArray(); } - if(architectures.Count > 0) Metadata.Architectures = architectures.ToArray(); - if(barcodes.Count > 0) Metadata.Barcodes = barcodes.ToArray(); - if(disks.Count > 0) Metadata.BlockMedia = disks.ToArray(); - if(categories.Count > 0) Metadata.Categories = categories.ToArray(); - if(keywords.Count > 0) Metadata.Keywords = keywords.ToArray(); - if(languages.Count > 0) Metadata.Languages = languages.ToArray(); - if(discs.Count > 0) Metadata.OpticalDisc = discs.ToArray(); - if(subcategories.Count > 0) Metadata.Subcategories = subcategories.ToArray(); - if(systems.Count > 0) Metadata.Systems = systems.ToArray(); + if(architectures.Count > 0) + Metadata.Architectures = architectures.ToArray(); + + if(barcodes.Count > 0) + Metadata.Barcodes = barcodes.ToArray(); + + if(disks.Count > 0) + Metadata.BlockMedia = disks.ToArray(); + + if(categories.Count > 0) + Metadata.Categories = categories.ToArray(); + + if(keywords.Count > 0) + Metadata.Keywords = keywords.ToArray(); + + if(languages.Count > 0) + Metadata.Languages = languages.ToArray(); + + if(discs.Count > 0) + Metadata.OpticalDisc = discs.ToArray(); + + if(subcategories.Count > 0) + Metadata.Subcategories = subcategories.ToArray(); + + if(systems.Count > 0) + Metadata.Systems = systems.ToArray(); Metadata.Magazine = magazines; Metadata.Book = books; @@ -1044,104 +1361,120 @@ namespace apprepodbmgr.Eto protected void OnBtnEditDiscClicked(object sender, EventArgs e) { - if(treeDiscs.SelectedItem == null) return; + if(treeDiscs.SelectedItem == null) + return; - dlgOpticalDisc _dlgOpticalDisc = new dlgOpticalDisc + var _dlgOpticalDisc = new dlgOpticalDisc { Title = $"Editing disc metadata for {((DiscEntry)treeDiscs.SelectedItem).path}", Metadata = ((DiscEntry)treeDiscs.SelectedItem).disc }; + _dlgOpticalDisc.FillFields(); _dlgOpticalDisc.ShowModal(this); - if(!_dlgOpticalDisc.Modified) return; + if(!_dlgOpticalDisc.Modified) + return; lstDiscs.Remove((DiscEntry)treeDiscs.SelectedItem); - lstDiscs.Add(new DiscEntry {path = _dlgOpticalDisc.Metadata.Image.Value, disc = _dlgOpticalDisc.Metadata}); + + lstDiscs.Add(new DiscEntry + { + path = _dlgOpticalDisc.Metadata.Image.Value, + disc = _dlgOpticalDisc.Metadata + }); } protected void OnBtnEditDiskClicked(object sender, EventArgs e) { - if(treeDisks.SelectedItem == null) return; + if(treeDisks.SelectedItem == null) + return; - dlgBlockMedia _dlgBlockMedia = new dlgBlockMedia + var _dlgBlockMedia = new dlgBlockMedia { Title = $"Editing disk metadata for {((DiskEntry)treeDisks.SelectedItem).path}", Metadata = ((DiskEntry)treeDisks.SelectedItem).disk }; + _dlgBlockMedia.FillFields(); _dlgBlockMedia.ShowModal(this); - if(!_dlgBlockMedia.Modified) return; + if(!_dlgBlockMedia.Modified) + return; lstDisks.Remove((DiskEntry)treeDisks.SelectedItem); - lstDisks.Add(new DiskEntry {path = _dlgBlockMedia.Metadata.Image.Value, disk = _dlgBlockMedia.Metadata}); + + lstDisks.Add(new DiskEntry + { + path = _dlgBlockMedia.Metadata.Image.Value, + disk = _dlgBlockMedia.Metadata + }); } #region XAML UI elements #pragma warning disable 0649 - TabPage tabGeneral; - TextBox txtDeveloper; - TextBox txtPublisher; - TextBox txtAuthor; - TextBox txtPerformer; - TextBox txtName; - TextBox txtVersion; - StackLayout stkReleaseType; - CheckBox chkKnownReleaseType; - EnumDropDown cmbReleaseType; - DateTimePicker cldReleaseDate; - CheckBox chkReleaseDate; - TextBox txtPartNumber; - TextBox txtSerialNumber; - TabPage tabKeywords; - TextBox txtNewKeyword; - GridView treeKeywords; - TabPage tabBarcodes; - TextBox txtNewBarcode; - ComboBox cmbBarcodes; - GridView treeBarcodes; - TabPage tabCategories; - TextBox txtNewCategory; - GridView treeCategories; - TextBox txtNewSubcategory; - GridView treeSubcategories; - TabPage tabLanguages; - ComboBox cmbLanguages; - GridView treeLanguages; - TabPage tabTargetOs; - TextBox txtNewOsName; - TextBox txtNewOsVersion; - GridView treeOses; - TabPage tabArchitectures; - ComboBox cmbArchitectures; - GridView treeArchitectures; - TabPage tabDiscs; - ComboBox cmbFilesForNewDisc; - Button btnAddDisc; - GridView treeDiscs; - Button btnStopAddDisc; - Button btnEditDisc; - Button btnClearDiscs; - Button btnRemoveDisc; - Label lblAddDisc1; - ProgressBar prgAddDisc1; - Label lblAddDisc2; - ProgressBar prgAddDisc2; - TabPage tabDisks; - ComboBox cmbFilesForNewDisk; - Button btnAddDisk; - GridView treeDisks; - Button btnStopAddDisk; - Button btnEditDisk; - Button btnClearDisks; - Button btnRemoveDisk; - Label lblAddDisk1; - ProgressBar prgAddDisk1; - Label lblAddDisk2; - ProgressBar prgAddDisk2; - Button btnCancel; - Button btnOK; + TabPage tabGeneral; + TextBox txtDeveloper; + TextBox txtPublisher; + TextBox txtAuthor; + TextBox txtPerformer; + TextBox txtName; + TextBox txtVersion; + StackLayout stkReleaseType; + CheckBox chkKnownReleaseType; + readonly EnumDropDown cmbReleaseType; + DateTimePicker cldReleaseDate; + CheckBox chkReleaseDate; + TextBox txtPartNumber; + TextBox txtSerialNumber; + TabPage tabKeywords; + TextBox txtNewKeyword; + GridView treeKeywords; + TabPage tabBarcodes; + TextBox txtNewBarcode; + ComboBox cmbBarcodes; + GridView treeBarcodes; + TabPage tabCategories; + TextBox txtNewCategory; + GridView treeCategories; + TextBox txtNewSubcategory; + GridView treeSubcategories; + TabPage tabLanguages; + ComboBox cmbLanguages; + GridView treeLanguages; + TabPage tabTargetOs; + TextBox txtNewOsName; + TextBox txtNewOsVersion; + GridView treeOses; + TabPage tabArchitectures; + ComboBox cmbArchitectures; + GridView treeArchitectures; + TabPage tabDiscs; + ComboBox cmbFilesForNewDisc; + Button btnAddDisc; + GridView treeDiscs; + Button btnStopAddDisc; + Button btnEditDisc; + Button btnClearDiscs; + Button btnRemoveDisc; + Label lblAddDisc1; + ProgressBar prgAddDisc1; + Label lblAddDisc2; + ProgressBar prgAddDisc2; + TabPage tabDisks; + ComboBox cmbFilesForNewDisk; + Button btnAddDisk; + GridView treeDisks; + Button btnStopAddDisk; + Button btnEditDisk; + Button btnClearDisks; + Button btnRemoveDisk; + Label lblAddDisk1; + ProgressBar prgAddDisk1; + Label lblAddDisk2; + ProgressBar prgAddDisk2; + Button btnCancel; + Button btnOK; #pragma warning restore 0649 #endregion XAML UI elements } diff --git a/apprepodbmgr.Eto/dlgOpticalDisc.xeto.cs b/apprepodbmgr.Eto/dlgOpticalDisc.xeto.cs index 5289280..0dd91e4 100644 --- a/apprepodbmgr.Eto/dlgOpticalDisc.xeto.cs +++ b/apprepodbmgr.Eto/dlgOpticalDisc.xeto.cs @@ -43,42 +43,42 @@ namespace apprepodbmgr.Eto DumpHardwareType dumpHwIter; bool editingDumpHw; - bool editingPartition; - FileSystemType filesystemIter; - ObservableCollection lstADIP; - ObservableCollection lstATIP; - ObservableCollection lstBCA; - ObservableCollection lstCDText; - ObservableCollection lstCMI; - ObservableCollection lstDCB; - ObservableCollection lstDDS; - ObservableCollection lstDI; - ObservableCollection lstDMI; + bool editingPartition; + FileSystemType filesystemIter; + readonly ObservableCollection lstADIP; + readonly ObservableCollection lstATIP; + readonly ObservableCollection lstBCA; + readonly ObservableCollection lstCDText; + readonly ObservableCollection lstCMI; + readonly ObservableCollection lstDCB; + readonly ObservableCollection lstDDS; + readonly ObservableCollection lstDI; + readonly ObservableCollection lstDMI; - ObservableCollection lstDumpHw; - ObservableCollection lstLastRMD; - ObservableCollection lstLayers; - ObservableCollection lstLeadIns; - ObservableCollection lstLeadOuts; - ObservableCollection lstMasteringSIDs; - ObservableCollection lstMediaID; - ObservableCollection lstMouldSIDs; - ObservableCollection lstMouldTexts; - ObservableCollection lstPAC; - ObservableCollection lstPFI; - ObservableCollection lstPFIR; - ObservableCollection lstPMA; - ObservableCollection lstPRI; - ObservableCollection lstRingCodes; - ObservableCollection lstSAI; - ObservableCollection lstTOC; - ObservableCollection lstToolstamps; - ObservableCollection lstTracks; - CaseType mediaCase; - public OpticalDiscType Metadata; - public bool Modified; - PartitionType partitionIter; - ScansType scans; + ObservableCollection lstDumpHw; + readonly ObservableCollection lstLastRMD; + ObservableCollection lstLayers; + ObservableCollection lstLeadIns; + ObservableCollection lstLeadOuts; + ObservableCollection lstMasteringSIDs; + readonly ObservableCollection lstMediaID; + ObservableCollection lstMouldSIDs; + ObservableCollection lstMouldTexts; + readonly ObservableCollection lstPAC; + readonly ObservableCollection lstPFI; + readonly ObservableCollection lstPFIR; + readonly ObservableCollection lstPMA; + readonly ObservableCollection lstPRI; + ObservableCollection lstRingCodes; + readonly ObservableCollection lstSAI; + readonly ObservableCollection lstTOC; + ObservableCollection lstToolstamps; + ObservableCollection lstTracks; + CaseType mediaCase; + public OpticalDiscType Metadata; + public bool Modified; + PartitionType partitionIter; + ScansType scans; TrackType trackIter; XboxType xbox; @@ -98,6 +98,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Sequence" }); + treePartitions.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -106,6 +107,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Start" }); + treePartitions.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -114,19 +116,31 @@ namespace apprepodbmgr.Eto }, HeaderText = "End" }); + treePartitions.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Type)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Type) + }, HeaderText = "Type" }); + treePartitions.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Name)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Name) + }, HeaderText = "Name" }); + treePartitions.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Description)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Description) + }, HeaderText = "Description" }); @@ -136,12 +150,19 @@ namespace apprepodbmgr.Eto #region Set filesystems table treeFilesystems.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Type)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Type) + }, HeaderText = "Type" }); + treeFilesystems.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.VolumeName)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.VolumeName) + }, HeaderText = "Name" }); @@ -153,30 +174,49 @@ namespace apprepodbmgr.Eto treeDumpHardware.Columns.Add(new GridColumn { - DataCell = - new TextBoxCell {Binding = Binding.Property(r => r.Manufacturer)}, - HeaderText = "Manufacturer" + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Manufacturer) + }, + HeaderText = "Manufacturer" }); + treeDumpHardware.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Model)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Model) + }, HeaderText = "Model" }); + treeDumpHardware.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Revision)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Revision) + }, HeaderText = "Revision" }); + treeDumpHardware.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Firmware)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Firmware) + }, HeaderText = "Firmware" }); + treeDumpHardware.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Serial)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Serial) + }, HeaderText = "Serial" }); + treeDumpHardware.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -185,6 +225,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Software" }); + treeDumpHardware.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -193,12 +234,13 @@ namespace apprepodbmgr.Eto }, HeaderText = "Version" }); + treeDumpHardware.Columns.Add(new GridColumn { DataCell = new TextBoxCell { - Binding = Binding.Property(r => r.Software) - .Convert(v => v?.OperatingSystem) + Binding = Binding.Property(r => r.Software). + Convert(v => v?.OperatingSystem) }, HeaderText = "Operating system" }); @@ -215,6 +257,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Start" }); + treeExtents.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -227,11 +270,16 @@ namespace apprepodbmgr.Eto #region Set TOC table lstTOC = new ObservableCollection(); + treeTOC.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeTOC.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -240,16 +288,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeTOC.DataStore = lstTOC; #endregion Set TOC table #region Set CD-Text table lstCDText = new ObservableCollection(); + treeCDText.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeCDText.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -258,16 +312,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeCDText.DataStore = lstCDText; #endregion Set CD-Text table #region Set ATIP table lstATIP = new ObservableCollection(); + treeATIP.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeATIP.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -276,16 +336,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeATIP.DataStore = lstATIP; #endregion Set ATIP table #region Set PMA table lstPMA = new ObservableCollection(); + treePMA.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treePMA.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -294,16 +360,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treePMA.DataStore = lstPMA; #endregion Set PMA table #region Set PFI table lstPFI = new ObservableCollection(); + treePFI.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treePFI.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -312,16 +384,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treePFI.DataStore = lstPFI; #endregion Set PFI table #region Set DMI table lstDMI = new ObservableCollection(); + treeDMI.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeDMI.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -330,16 +408,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeDMI.DataStore = lstDMI; #endregion Set DMI table #region Set CMI table lstCMI = new ObservableCollection(); + treeCMI.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeCMI.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -348,16 +432,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeCMI.DataStore = lstCMI; #endregion Set CMI table #region Set BCA table lstBCA = new ObservableCollection(); + treeBCA.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeBCA.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -366,16 +456,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeBCA.DataStore = lstBCA; #endregion Set BCA table #region Set DCB table lstDCB = new ObservableCollection(); + treeDCB.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeDCB.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -384,16 +480,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeDCB.DataStore = lstDCB; #endregion Set DCB table #region Set PRI table lstPRI = new ObservableCollection(); + treePRI.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treePRI.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -402,16 +504,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treePRI.DataStore = lstPRI; #endregion Set PRI table #region Set MediaID table lstMediaID = new ObservableCollection(); + treeMediaID.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeMediaID.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -420,16 +528,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeMediaID.DataStore = lstMediaID; #endregion Set MediaID table #region Set PFIR table lstPFIR = new ObservableCollection(); + treePFIR.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treePFIR.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -438,16 +552,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treePFIR.DataStore = lstPFIR; #endregion Set PFIR table #region Set LastRMD table lstLastRMD = new ObservableCollection(); + treeLastRMD.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeLastRMD.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -456,16 +576,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeLastRMD.DataStore = lstLastRMD; #endregion Set LastRMD table #region Set ADIP table lstADIP = new ObservableCollection(); + treeADIP.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeADIP.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -474,16 +600,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeADIP.DataStore = lstADIP; #endregion Set ADIP table #region Set DDS table lstDDS = new ObservableCollection(); + treeDDS.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeDDS.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -492,16 +624,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeDDS.DataStore = lstDDS; #endregion Set DDS table #region Set SAI table lstSAI = new ObservableCollection(); + treeSAI.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeSAI.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -510,16 +648,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeSAI.DataStore = lstSAI; #endregion Set SAI table #region Set DI table lstDI = new ObservableCollection(); + treeDI.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeDI.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -528,16 +672,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeDI.DataStore = lstDI; #endregion Set DI table #region Set PAC table lstPAC = new ObservableCollection(); + treePAC.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treePAC.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -546,11 +696,13 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treePAC.DataStore = lstPAC; #endregion Set PAC table #region Set ring code table lstRingCodes = new ObservableCollection(); + treeRingCodes.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -559,16 +711,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Layer" }); + treeRingCodes.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Value)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Value) + }, HeaderText = "Code" }); + treeRingCodes.DataStore = lstRingCodes; #endregion Set ring code table #region Set mastering sid table lstMasteringSIDs = new ObservableCollection(); + treeMasteringSIDs.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -577,16 +735,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Layer" }); + treeMasteringSIDs.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Value)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Value) + }, HeaderText = "Code" }); + treeMasteringSIDs.DataStore = lstMasteringSIDs; #endregion Set mastering sid table #region Set toolstamp table lstToolstamps = new ObservableCollection(); + treeToolstamps.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -595,16 +759,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Layer" }); + treeToolstamps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Value)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Value) + }, HeaderText = "Code" }); + treeToolstamps.DataStore = lstToolstamps; #endregion Set toolstamp table #region Set mould sid table lstMouldSIDs = new ObservableCollection(); + treeMouldSIDs.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -613,16 +783,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Layer" }); + treeMouldSIDs.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Value)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Value) + }, HeaderText = "Code" }); + treeMouldSIDs.DataStore = lstMouldSIDs; #endregion Set mould sid table #region Set mould text table lstMouldTexts = new ObservableCollection(); + treeMouldTexts.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -631,17 +807,26 @@ namespace apprepodbmgr.Eto }, HeaderText = "Layer" }); + treeMouldTexts.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Value)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Value) + }, HeaderText = "Code" }); + treeMouldTexts.DataStore = lstMouldTexts; #endregion Set mould text table #region Set layer type combo box - cmbLayerType = new EnumDropDown(); - stkLayers.Items.Add(new StackLayoutItem {Control = cmbLayerType}); + cmbLayerType = new EnumDropDown(); + + stkLayers.Items.Add(new StackLayoutItem + { + Control = cmbLayerType + }); #endregion Set layer type combo box #region Set layers table @@ -655,6 +840,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Layer" }); + treeLayers.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -671,11 +857,16 @@ namespace apprepodbmgr.Eto #region Set Lead-In table lstLeadIns = new ObservableCollection(); + treeLeadIn.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeLeadIn.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -684,6 +875,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeLeadIn.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -692,16 +884,22 @@ namespace apprepodbmgr.Eto }, HeaderText = "Session" }); + treeLeadIn.DataStore = lstLeadIns; #endregion Set Lead-In table #region Set Lead-Out table lstLeadOuts = new ObservableCollection(); + treeLeadOut.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image) + }, HeaderText = "File" }); + treeLeadOut.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -710,6 +908,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeLeadOut.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -718,6 +917,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Session" }); + treeLeadOut.DataStore = lstLeadOuts; #endregion Set Lead-Out table @@ -732,6 +932,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "Track" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -740,11 +941,16 @@ namespace apprepodbmgr.Eto }, HeaderText = "Session" }); + treeTracks.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image.Value)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image.Value) + }, HeaderText = "File" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -753,11 +959,16 @@ namespace apprepodbmgr.Eto }, HeaderText = "Size" }); + treeTracks.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Image.format)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Image.format) + }, HeaderText = "Format" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -766,16 +977,25 @@ namespace apprepodbmgr.Eto }, HeaderText = "Offset" }); + treeTracks.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.StartMSF)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.StartMSF) + }, HeaderText = "MSF Start" }); + treeTracks.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.EndMSF)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.EndMSF) + }, HeaderText = "MSF End" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -784,6 +1004,7 @@ namespace apprepodbmgr.Eto }, HeaderText = "LBA Start" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -792,15 +1013,17 @@ namespace apprepodbmgr.Eto }, HeaderText = "LBA End" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell { - Binding = Binding.Property(r => r.TrackType1) - .Convert(v => v.ToString()) + Binding = Binding.Property(r => r.TrackType1). + Convert(v => v.ToString()) }, HeaderText = "Type" }); + treeTracks.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -809,9 +1032,13 @@ namespace apprepodbmgr.Eto }, HeaderText = "Bytes per sector" }); + treeTracks.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.AccoustID)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.AccoustID) + }, HeaderText = "Accoust ID" }); @@ -823,56 +1050,65 @@ namespace apprepodbmgr.Eto spExtentStart.MaxValue = double.MaxValue; spExtentEnd.MaxValue = double.MaxValue; - txtImage.ToolTip = "This is the disc image containing this media."; - txtFormat.ToolTip = "This is the format of the disc image."; - txtOffset.ToolTip = "Byte offset where the media dump starts in the disc image."; - txtSize.ToolTip = "Size of the disc dump."; - txtWriteOffset.ToolTip = "Write offset in bytes (can be negative)."; - txtMediaTracks.ToolTip = "How many tracks?"; - txtMediaSessions.ToolTip = "How many sessions?"; + txtImage.ToolTip = "This is the disc image containing this media."; + txtFormat.ToolTip = "This is the format of the disc image."; + txtOffset.ToolTip = "Byte offset where the media dump starts in the disc image."; + txtSize.ToolTip = "Size of the disc dump."; + txtWriteOffset.ToolTip = "Write offset in bytes (can be negative)."; + txtMediaTracks.ToolTip = "How many tracks?"; + txtMediaSessions.ToolTip = "How many sessions?"; txtCopyProtection.ToolTip = "Disc copy protection."; - txtDiscType.ToolTip = "Disc type."; - txtDiscSubtype.ToolTip = "Disc subtype."; - chkSequence.ToolTip = "If checked means this disc is one in a sequence of several."; - txtDiscTitle.ToolTip = "Title of disc."; - spSequence.ToolTip = "Number of this disc in the sequence."; - spTotalMedia.ToolTip = "How many diskc make the sequence."; - spSide.ToolTip = "On double sided discs, which side of the disc is represented by this dump."; - spLayer.ToolTip = "On PTP layered discs, which layer of the side of the disc is represented by this dump."; - chkDimensions.ToolTip = "If checked, physical dimensions of disk are known."; - chkRound.ToolTip = "If checked, disk is physicaly round."; - spDiameter.ToolTip = "Diameter in milimeters of disk."; - spHeight.ToolTip = "Height in milimeters of disk."; - spWidth.ToolTip = "Width in milimeters of disk."; - spThickness.ToolTip = "Thickness in milimeters of disk."; + txtDiscType.ToolTip = "Disc type."; + txtDiscSubtype.ToolTip = "Disc subtype."; + chkSequence.ToolTip = "If checked means this disc is one in a sequence of several."; + txtDiscTitle.ToolTip = "Title of disc."; + spSequence.ToolTip = "Number of this disc in the sequence."; + spTotalMedia.ToolTip = "How many diskc make the sequence."; + spSide.ToolTip = "On double sided discs, which side of the disc is represented by this dump."; + spLayer.ToolTip = "On PTP layered discs, which layer of the side of the disc is represented by this dump."; + chkDimensions.ToolTip = "If checked, physical dimensions of disk are known."; + chkRound.ToolTip = "If checked, disk is physicaly round."; + spDiameter.ToolTip = "Diameter in milimeters of disk."; + spHeight.ToolTip = "Height in milimeters of disk."; + spWidth.ToolTip = "Width in milimeters of disk."; + spThickness.ToolTip = "Thickness in milimeters of disk."; } public void FillFields() { - if(Metadata == null) return; + if(Metadata == null) + return; + + txtImage.Text = Metadata.Image.Value; + txtFormat.Text = Metadata.Image.format; + + if(Metadata.Image.offsetSpecified) + txtOffset.Text = Metadata.Image.offset.ToString(); + + txtSize.Text = Metadata.Size.ToString(); - txtImage.Text = Metadata.Image.Value; - txtFormat.Text = Metadata.Image.format; - if(Metadata.Image.offsetSpecified) txtOffset.Text = Metadata.Image.offset.ToString(); - txtSize.Text = Metadata.Size.ToString(); if(Metadata.Sequence != null) { - lblDiscTitle.Visible = true; - lblDiscTitle.Visible = true; - lblSequence.Visible = true; - spSequence.Visible = true; - lblTotalMedia.Visible = true; - spTotalMedia.Visible = true; - lblSide.Visible = true; - spSide.Visible = true; - lblLayer.Visible = true; - spLayer.Visible = true; - chkSequence.Checked = true; - txtDiscTitle.Text = Metadata.Sequence.MediaTitle; - spSequence.Value = Metadata.Sequence.MediaSequence; - spTotalMedia.Value = Metadata.Sequence.TotalMedia; - if(Metadata.Sequence.SideSpecified) spSide.Value = Metadata.Sequence.Side; - if(Metadata.Sequence.LayerSpecified) spLayer.Value = Metadata.Sequence.Layer; + lblDiscTitle.Visible = true; + lblDiscTitle.Visible = true; + lblSequence.Visible = true; + spSequence.Visible = true; + lblTotalMedia.Visible = true; + spTotalMedia.Visible = true; + lblSide.Visible = true; + spSide.Visible = true; + lblLayer.Visible = true; + spLayer.Visible = true; + chkSequence.Checked = true; + txtDiscTitle.Text = Metadata.Sequence.MediaTitle; + spSequence.Value = Metadata.Sequence.MediaSequence; + spTotalMedia.Value = Metadata.Sequence.TotalMedia; + + if(Metadata.Sequence.SideSpecified) + spSide.Value = Metadata.Sequence.Side; + + if(Metadata.Sequence.LayerSpecified) + spLayer.Value = Metadata.Sequence.Layer; } if(Metadata.Layers != null) @@ -918,16 +1154,25 @@ namespace apprepodbmgr.Eto treeMouldTexts.DataStore = lstMouldTexts; } - if(Metadata.DiscType != null) txtDiscType.Text = Metadata.DiscType; - if(Metadata.DiscSubType != null) txtDiscSubtype.Text = Metadata.DiscSubType; - if(Metadata.OffsetSpecified) txtWriteOffset.Text = Metadata.Offset.ToString(); - txtMediaTracks.Text = Metadata.Tracks[0].ToString(); - txtMediaSessions.Text = Metadata.Sessions.ToString(); - if(Metadata.CopyProtection != null) txtCopyProtection.Text = Metadata.CopyProtection; + if(Metadata.DiscType != null) + txtDiscType.Text = Metadata.DiscType; + + if(Metadata.DiscSubType != null) + txtDiscSubtype.Text = Metadata.DiscSubType; + + if(Metadata.OffsetSpecified) + txtWriteOffset.Text = Metadata.Offset.ToString(); + + txtMediaTracks.Text = Metadata.Tracks[0].ToString(); + txtMediaSessions.Text = Metadata.Sessions.ToString(); + + if(Metadata.CopyProtection != null) + txtCopyProtection.Text = Metadata.CopyProtection; if(Metadata.Dimensions != null) { chkDimensions.Checked = true; + if(Metadata.Dimensions.DiameterSpecified) { chkRound.Checked = true; @@ -1111,7 +1356,9 @@ namespace apprepodbmgr.Eto { chkRound.Visible = chkDimensions.Checked.Value; stkThickness.Visible = chkDimensions.Checked.Value; - if(chkDimensions.Checked.Value) OnChkRoundToggled(sender, e); + + if(chkDimensions.Checked.Value) + OnChkRoundToggled(sender, e); else { stkDiameter.Visible = false; @@ -1127,25 +1374,23 @@ namespace apprepodbmgr.Eto stkWidth.Visible = !chkRound.Checked.Value; } - protected void OnChkLayersToggled(object sender, EventArgs e) - { - frmLayers.Visible = chkLayers.Checked.Value; - } + protected void OnChkLayersToggled(object sender, EventArgs e) => frmLayers.Visible = chkLayers.Checked.Value; - static void ErrorMessageBox(string text) - { - MessageBox.Show(text, MessageBoxType.Error); - } + static void ErrorMessageBox(string text) => MessageBox.Show(text, MessageBoxType.Error); protected void OnBtnAddLayerClicked(object sender, EventArgs e) { - if(string.IsNullOrWhiteSpace(txtLayerSize.Text)) ErrorMessageBox("Layer size must not be empty"); + if(string.IsNullOrWhiteSpace(txtLayerSize.Text)) + ErrorMessageBox("Layer size must not be empty"); - if(!long.TryParse(txtLayerSize.Text, out long ltmp)) ErrorMessageBox("Layer size must be a number"); + if(!long.TryParse(txtLayerSize.Text, out long ltmp)) + ErrorMessageBox("Layer size must be a number"); - if(ltmp < 0) ErrorMessageBox("Layer size must be a positive"); + if(ltmp < 0) + ErrorMessageBox("Layer size must be a positive"); - if(ltmp == 0) ErrorMessageBox("Layer size must be bigger than 0"); + if(ltmp == 0) + ErrorMessageBox("Layer size must be bigger than 0"); lstLayers.Add(new SectorsType { @@ -1157,19 +1402,21 @@ namespace apprepodbmgr.Eto protected void OnBtnRemoveLayerClicked(object sender, EventArgs e) { - if(treeLayers.SelectedItem != null) lstLayers.Remove((SectorsType)treeLayers.SelectedItem); + if(treeLayers.SelectedItem != null) + lstLayers.Remove((SectorsType)treeLayers.SelectedItem); } protected void OnBtnRemovePartitionClicked(object sender, EventArgs e) { if(treePartitions.SelectedItem != null) - ((ObservableCollection)treePartitions.DataStore).Remove((PartitionType)treePartitions - .SelectedItem); + ((ObservableCollection)treePartitions.DataStore).Remove((PartitionType)treePartitions. + SelectedItem); } protected void OnBtnEditPartitionClicked(object sender, EventArgs e) { - if(treePartitions.SelectedItem == null) return; + if(treePartitions.SelectedItem == null) + return; partitionIter = (PartitionType)treePartitions.SelectedItem; @@ -1179,9 +1426,11 @@ namespace apprepodbmgr.Eto txtPartitionType.Text = partitionIter.Type; txtPartitionName.Text = partitionIter.Name; txtPartitionDescription.Text = partitionIter.Description; - treeFilesystems.DataStore = partitionIter.FileSystems != null - ? new ObservableCollection(partitionIter.FileSystems) - : new ObservableCollection(); + + treeFilesystems.DataStore = partitionIter.FileSystems != null + ? new ObservableCollection(partitionIter.FileSystems) + : new ObservableCollection(); + btnCancelPartition.Visible = true; btnApplyPartition.Visible = true; btnRemovePartition.Visible = false; @@ -1199,22 +1448,27 @@ namespace apprepodbmgr.Eto if(!int.TryParse(txtPartitionStart.Text, out int temp)) { ErrorMessageBox("Partition start must be a number"); + return; } if(!int.TryParse(txtPartitionEnd.Text, out int temp2)) { ErrorMessageBox("Partition end must be a number"); + return; } if(temp2 <= temp) { ErrorMessageBox("Partition must end after start, and be bigger than 1 sector"); + return; } - if(editingPartition) ((ObservableCollection)treePartitions.DataStore).Remove(partitionIter); + if(editingPartition) + ((ObservableCollection)treePartitions.DataStore).Remove(partitionIter); + partitionIter = new PartitionType { Sequence = (int)spPartitionSequence.Value, @@ -1224,6 +1478,7 @@ namespace apprepodbmgr.Eto Name = txtPartitionName.Text, Description = txtPartitionDescription.Text }; + if(((ObservableCollection)treeFilesystems.DataStore).Count > 0) partitionIter.FileSystems = ((ObservableCollection)treeFilesystems.DataStore).ToArray(); @@ -1263,21 +1518,27 @@ namespace apprepodbmgr.Eto protected void OnBtnRemoveFilesystemClicked(object sender, EventArgs e) { if(treeFilesystems.SelectedItem != null) - ((ObservableCollection)treeFilesystems.DataStore).Remove((FileSystemType)treeFilesystems - .SelectedItem); + ((ObservableCollection)treeFilesystems.DataStore). + Remove((FileSystemType)treeFilesystems.SelectedItem); } protected void OnBtnEditFilesystemClicked(object sender, EventArgs e) { - if(treeFilesystems.SelectedItem == null) return; + if(treeFilesystems.SelectedItem == null) + return; filesystemIter = (FileSystemType)treeFilesystems.SelectedItem; - dlgFilesystem _dlgFilesystem = new dlgFilesystem {Metadata = filesystemIter}; + var _dlgFilesystem = new dlgFilesystem + { + Metadata = filesystemIter + }; + _dlgFilesystem.FillFields(); _dlgFilesystem.ShowModal(this); - if(!_dlgFilesystem.Modified) return; + if(!_dlgFilesystem.Modified) + return; ((ObservableCollection)treeFilesystems.DataStore).Remove(filesystemIter); ((ObservableCollection)treeFilesystems.DataStore).Add(_dlgFilesystem.Metadata); @@ -1285,7 +1546,7 @@ namespace apprepodbmgr.Eto protected void OnBtnAddFilesystemClicked(object sender, EventArgs e) { - dlgFilesystem _dlgFilesystem = new dlgFilesystem(); + var _dlgFilesystem = new dlgFilesystem(); _dlgFilesystem.ShowModal(this); if(_dlgFilesystem.Modified) @@ -1306,41 +1567,46 @@ namespace apprepodbmgr.Eto protected void OnBtnApplyTrackClicked(object sender, EventArgs e) { - string file = trackIter.Image.Value; - long filesize = trackIter.Size; - string fileformat = trackIter.Image.format; - long fileoffset = trackIter.Image.offset; - ChecksumType[] checksums = trackIter.Checksums; - SubChannelType subchannel = trackIter.SubChannel; - TrackTypeTrackType trackType = - (TrackTypeTrackType)Enum.Parse(typeof(TrackTypeTrackType), cmbTrackType.Text); + string file = trackIter.Image.Value; + long filesize = trackIter.Size; + string fileformat = trackIter.Image.format; + long fileoffset = trackIter.Image.offset; + ChecksumType[] checksums = trackIter.Checksums; + SubChannelType subchannel = trackIter.SubChannel; + var trackType = (TrackTypeTrackType)Enum.Parse(typeof(TrackTypeTrackType), cmbTrackType.Text); lstTracks.Remove(trackIter); trackIter = new TrackType { - AccoustID = txtAcoustID.Text, - BytesPerSector = int.Parse(txtBytesPerSector.Text), - Checksums = checksums, - EndMSF = txtMSFEnd.Text, - EndSector = long.Parse(txtTrackEnd.Text), - Image = - new ImageType {format = fileformat, offset = fileoffset, offsetSpecified = true, Value = file}, - Sequence = - new TrackSequenceType - { - Session = int.Parse(txtSessionSequence.Text), - TrackNumber = int.Parse(txtTrackSequence.Text) - }, + AccoustID = txtAcoustID.Text, + BytesPerSector = int.Parse(txtBytesPerSector.Text), + Checksums = checksums, + EndMSF = txtMSFEnd.Text, + EndSector = long.Parse(txtTrackEnd.Text), + Image = new ImageType + { + format = fileformat, + offset = fileoffset, + offsetSpecified = true, + Value = file + }, + Sequence = new TrackSequenceType + { + Session = int.Parse(txtSessionSequence.Text), + TrackNumber = int.Parse(txtTrackSequence.Text) + }, Size = filesize, StartMSF = txtMSFStart.Text, StartSector = long.Parse(txtTrackStart.Text), SubChannel = subchannel, TrackType1 = trackType }; + if(((ObservableCollection)treePartitions.DataStore).Count > 0) trackIter.FileSystemInformation = ((ObservableCollection)treePartitions.DataStore).ToArray(); + lstTracks.Add(trackIter); btnEditTrack.Visible = true; @@ -1354,7 +1620,8 @@ namespace apprepodbmgr.Eto protected void OnBtnEditTrackClicked(object sender, EventArgs e) { - if(treeTracks.SelectedItem == null) return; + if(treeTracks.SelectedItem == null) + return; trackIter = (TrackType)treeTracks.SelectedItem; @@ -1402,12 +1669,14 @@ namespace apprepodbmgr.Eto protected void OnBtnRemoveHardwareClicked(object sender, EventArgs e) { - if(treeDumpHardware.SelectedItem != null) lstDumpHw.Remove((DumpHardwareType)treeDumpHardware.SelectedItem); + if(treeDumpHardware.SelectedItem != null) + lstDumpHw.Remove((DumpHardwareType)treeDumpHardware.SelectedItem); } protected void OnBtnApplyHardwareClicked(object sender, EventArgs e) { - if(editingDumpHw) lstDumpHw.Remove(dumpHwIter); + if(editingDumpHw) + lstDumpHw.Remove(dumpHwIter); dumpHwIter = new DumpHardwareType { @@ -1417,7 +1686,9 @@ namespace apprepodbmgr.Eto Firmware = txtHWFirmware.Text, Serial = txtHWSerial.Text }; - if(!string.IsNullOrWhiteSpace(txtDumpName.Text) || !string.IsNullOrWhiteSpace(txtDumpVersion.Text) || + + if(!string.IsNullOrWhiteSpace(txtDumpName.Text) || + !string.IsNullOrWhiteSpace(txtDumpVersion.Text) || !string.IsNullOrWhiteSpace(txtDumpOS.Text)) dumpHwIter.Software = new SoftwareType { @@ -1425,6 +1696,7 @@ namespace apprepodbmgr.Eto Version = txtDumpVersion.Text, OperatingSystem = txtDumpOS.Text }; + if(((ObservableCollection)treeExtents.DataStore).Count > 0) dumpHwIter.Extents = ((ObservableCollection)treeExtents.DataStore).ToArray(); @@ -1468,7 +1740,8 @@ namespace apprepodbmgr.Eto protected void OnBtnEditHardwareClicked(object sender, EventArgs e) { - if(treeDumpHardware.SelectedItem == null) return; + if(treeDumpHardware.SelectedItem == null) + return; dumpHwIter = (DumpHardwareType)treeDumpHardware.SelectedItem; @@ -1477,6 +1750,7 @@ namespace apprepodbmgr.Eto txtHWRevision.Text = dumpHwIter.Revision; txtHWFirmware.Text = dumpHwIter.Firmware; txtHWSerial.Text = dumpHwIter.Serial; + if(dumpHwIter.Software != null) { txtDumpName.Text = dumpHwIter.Software.Name; @@ -1496,39 +1770,33 @@ namespace apprepodbmgr.Eto editingDumpHw = true; } - protected void OnBtnAddExtentClicked(object sender, EventArgs e) - { + protected void OnBtnAddExtentClicked(object sender, EventArgs e) => ((ObservableCollection)treeExtents.DataStore).Add(new ExtentType { Start = (ulong)spExtentStart.Value, End = (ulong)spExtentEnd.Value }); - } - protected void OnBtnAddRingCodeClicked(object sender, EventArgs e) + protected void OnBtnAddRingCodeClicked(object sender, EventArgs e) => lstRingCodes.Add(new LayeredTextType { - lstRingCodes.Add(new LayeredTextType - { - layer = (int)spRingCodeLayer.Value, - layerSpecified = true, - Value = txtRingCode.Text - }); - } + layer = (int)spRingCodeLayer.Value, + layerSpecified = true, + Value = txtRingCode.Text + }); protected void OnBtnRemoveRingCodeClicked(object sender, EventArgs e) { - if(treeRingCodes.SelectedItem != null) lstRingCodes.Remove((LayeredTextType)treeRingCodes.SelectedItem); + if(treeRingCodes.SelectedItem != null) + lstRingCodes.Remove((LayeredTextType)treeRingCodes.SelectedItem); } - protected void OnBtnAddMasteringSIDClicked(object sender, EventArgs e) - { + protected void OnBtnAddMasteringSIDClicked(object sender, EventArgs e) => lstMasteringSIDs.Add(new LayeredTextType { layer = (int)spMasteringSIDLayer.Value, layerSpecified = true, Value = txtMasteringSID.Text }); - } protected void OnBtnRemoveMasteringSIDClicked(object sender, EventArgs e) { @@ -1536,49 +1804,43 @@ namespace apprepodbmgr.Eto lstMasteringSIDs.Remove((LayeredTextType)treeMasteringSIDs.SelectedItem); } - protected void OnBtnAddToolstampClicked(object sender, EventArgs e) + protected void OnBtnAddToolstampClicked(object sender, EventArgs e) => lstToolstamps.Add(new LayeredTextType { - lstToolstamps.Add(new LayeredTextType - { - layer = (int)spToolstampLayer.Value, - layerSpecified = true, - Value = txtToolstamp.Text - }); - } + layer = (int)spToolstampLayer.Value, + layerSpecified = true, + Value = txtToolstamp.Text + }); protected void OnBtnRemoveToolstampClicked(object sender, EventArgs e) { - if(treeToolstamps.SelectedItem != null) lstToolstamps.Remove((LayeredTextType)treeToolstamps.SelectedItem); + if(treeToolstamps.SelectedItem != null) + lstToolstamps.Remove((LayeredTextType)treeToolstamps.SelectedItem); } - protected void OnBtnAddMouldSIDClicked(object sender, EventArgs e) + protected void OnBtnAddMouldSIDClicked(object sender, EventArgs e) => lstMouldSIDs.Add(new LayeredTextType { - lstMouldSIDs.Add(new LayeredTextType - { - layer = (int)spMouldSIDLayer.Value, - layerSpecified = true, - Value = txtMouldSID.Text - }); - } + layer = (int)spMouldSIDLayer.Value, + layerSpecified = true, + Value = txtMouldSID.Text + }); protected void OnBtnRemoveMouldSIDClicked(object sender, EventArgs e) { - if(treeMouldSIDs.SelectedItem != null) lstMouldSIDs.Remove((LayeredTextType)treeMouldSIDs.SelectedItem); + if(treeMouldSIDs.SelectedItem != null) + lstMouldSIDs.Remove((LayeredTextType)treeMouldSIDs.SelectedItem); } - protected void OnBtnAddMouldTextClicked(object sender, EventArgs e) + protected void OnBtnAddMouldTextClicked(object sender, EventArgs e) => lstMouldTexts.Add(new LayeredTextType { - lstMouldTexts.Add(new LayeredTextType - { - layer = (int)spMouldTextLayer.Value, - layerSpecified = true, - Value = txtMouldText.Text - }); - } + layer = (int)spMouldTextLayer.Value, + layerSpecified = true, + Value = txtMouldText.Text + }); protected void OnBtnRemoveMouldTextClicked(object sender, EventArgs e) { - if(treeMouldTexts.SelectedItem != null) lstMouldTexts.Remove((LayeredTextType)treeMouldTexts.SelectedItem); + if(treeMouldTexts.SelectedItem != null) + lstMouldTexts.Remove((LayeredTextType)treeMouldTexts.SelectedItem); } protected void OnBtnSaveClicked(object sender, EventArgs e) @@ -1587,6 +1849,7 @@ namespace apprepodbmgr.Eto if(string.IsNullOrEmpty(txtFormat.Text)) { ErrorMessageBox("Image format cannot be null"); + return; } @@ -1595,49 +1858,60 @@ namespace apprepodbmgr.Eto if(spSequence.Value < 1) { ErrorMessageBox("Media sequence must be bigger than 0"); + return; } if(spTotalMedia.Value < 1) { ErrorMessageBox("Total medias must be bigger than 0"); + return; } if(spSequence.Value > spTotalMedia.Value) { ErrorMessageBox("Media sequence cannot be bigger than total medias"); + return; } } - if(!string.IsNullOrEmpty(txtWriteOffset.Text) && !long.TryParse(txtWriteOffset.Text, out long ltmp)) + if(!string.IsNullOrEmpty(txtWriteOffset.Text) && + !long.TryParse(txtWriteOffset.Text, out long ltmp)) { ErrorMessageBox("Write offset must be a number"); + return; } - if(string.IsNullOrEmpty(txtMediaTracks.Text) || !long.TryParse(txtMediaTracks.Text, out ltmp)) + if(string.IsNullOrEmpty(txtMediaTracks.Text) || + !long.TryParse(txtMediaTracks.Text, out ltmp)) { ErrorMessageBox("Tracks must be a number"); + return; } if(ltmp < 1) { ErrorMessageBox("Tracks must be bigger than 0"); + return; } - if(string.IsNullOrEmpty(txtMediaSessions.Text) || !long.TryParse(txtMediaSessions.Text, out ltmp)) + if(string.IsNullOrEmpty(txtMediaSessions.Text) || + !long.TryParse(txtMediaSessions.Text, out ltmp)) { ErrorMessageBox("Sessions must be a number"); + return; } if(ltmp < 1) { ErrorMessageBox("Sessions must be bigger than 0"); + return; } @@ -1648,6 +1922,7 @@ namespace apprepodbmgr.Eto if(spDiameter.Value <= 0) { ErrorMessageBox("Diameter must be bigger than 0"); + return; } } @@ -1656,12 +1931,14 @@ namespace apprepodbmgr.Eto if(spHeight.Value <= 0) { ErrorMessageBox("Height must be bigger than 0"); + return; } if(spWidth.Value <= 0) { ErrorMessageBox("Width must be bigger than 0"); + return; } } @@ -1669,6 +1946,7 @@ namespace apprepodbmgr.Eto if(spThickness.Value <= 0) { ErrorMessageBox("Thickness must be bigger than 0"); + return; } } @@ -1677,13 +1955,22 @@ namespace apprepodbmgr.Eto if(lstDumpHw.Count < 1) { ErrorMessageBox("If dump hardware is known at least an entry must be created"); + return; } #endregion Sanity checks - Metadata = new OpticalDiscType {Image = new ImageType {Value = txtImage.Text, format = txtFormat.Text}}; + Metadata = new OpticalDiscType + { + Image = new ImageType + { + Value = txtImage.Text, + format = txtFormat.Text + } + }; - if(!string.IsNullOrWhiteSpace(txtOffset.Text) && long.TryParse(txtOffset.Text, out ltmp)) + if(!string.IsNullOrWhiteSpace(txtOffset.Text) && + long.TryParse(txtOffset.Text, out ltmp)) { Metadata.Image.offsetSpecified = true; Metadata.Image.offset = long.Parse(txtOffset.Text); @@ -1699,6 +1986,7 @@ namespace apprepodbmgr.Eto MediaSequence = (int)spSequence.Value, TotalMedia = (int)spTotalMedia.Value }; + if(spSide.Value > 0) { Metadata.Sequence.SideSpecified = true; @@ -1723,36 +2011,51 @@ namespace apprepodbmgr.Eto Metadata.Checksums = checksums; Metadata.Xbox = xbox; - if(lstRingCodes.Count > 0) Metadata.RingCode = lstRingCodes.ToArray(); + if(lstRingCodes.Count > 0) + Metadata.RingCode = lstRingCodes.ToArray(); - if(lstMasteringSIDs.Count > 0) Metadata.MasteringSID = lstMasteringSIDs.ToArray(); + if(lstMasteringSIDs.Count > 0) + Metadata.MasteringSID = lstMasteringSIDs.ToArray(); - if(lstToolstamps.Count > 0) Metadata.Toolstamp = lstToolstamps.ToArray(); + if(lstToolstamps.Count > 0) + Metadata.Toolstamp = lstToolstamps.ToArray(); - if(lstMouldSIDs.Count > 0) Metadata.MouldSID = lstMouldSIDs.ToArray(); + if(lstMouldSIDs.Count > 0) + Metadata.MouldSID = lstMouldSIDs.ToArray(); - if(lstMouldTexts.Count > 0) Metadata.MouldText = lstMouldTexts.ToArray(); + if(lstMouldTexts.Count > 0) + Metadata.MouldText = lstMouldTexts.ToArray(); + + if(!string.IsNullOrWhiteSpace(txtDiscType.Text)) + Metadata.DiscType = txtDiscType.Text; + + if(!string.IsNullOrWhiteSpace(txtDiscSubtype.Text)) + Metadata.DiscSubType = txtDiscSubtype.Text; - if(!string.IsNullOrWhiteSpace(txtDiscType.Text)) Metadata.DiscType = txtDiscType.Text; - if(!string.IsNullOrWhiteSpace(txtDiscSubtype.Text)) Metadata.DiscSubType = txtDiscSubtype.Text; if(!string.IsNullOrWhiteSpace(txtWriteOffset.Text)) { Metadata.Offset = int.Parse(txtWriteOffset.Text); Metadata.OffsetSpecified = true; } - Metadata.Tracks = !string.IsNullOrWhiteSpace(txtMediaTracks.Text) - ? new[] {int.Parse(txtMediaTracks.Text)} - : new[] {1}; + Metadata.Tracks = !string.IsNullOrWhiteSpace(txtMediaTracks.Text) ? new[] + { + int.Parse(txtMediaTracks.Text) + } : new[] + { + 1 + }; Metadata.Sessions = !string.IsNullOrWhiteSpace(txtMediaSessions.Text) ? int.Parse(txtMediaSessions.Text) : 1; - if(!string.IsNullOrWhiteSpace(txtCopyProtection.Text)) Metadata.CopyProtection = txtCopyProtection.Text; + if(!string.IsNullOrWhiteSpace(txtCopyProtection.Text)) + Metadata.CopyProtection = txtCopyProtection.Text; if(chkDimensions.Checked.Value) { Metadata.Dimensions = new DimensionsType(); + if(chkRound.Checked.Value) { Metadata.Dimensions.DiameterSpecified = true; @@ -1772,43 +2075,85 @@ namespace apprepodbmgr.Eto Metadata.Case = mediaCase; Metadata.Scans = scans; - if(lstPFI.Count == 1) Metadata.PFI = lstPFI[0]; - if(lstDMI.Count == 1) Metadata.DMI = lstDMI[0]; - if(lstCMI.Count == 1) Metadata.CMI = lstCMI[0]; - if(lstBCA.Count == 1) Metadata.BCA = lstBCA[0]; - if(lstATIP.Count == 1) Metadata.ATIP = lstATIP[0]; - if(lstADIP.Count == 1) Metadata.ADIP = lstADIP[0]; - if(lstPMA.Count == 1) Metadata.PMA = lstPMA[0]; - if(lstDDS.Count == 1) Metadata.DDS = lstDDS[0]; - if(lstSAI.Count == 1) Metadata.SAI = lstSAI[0]; - if(lstLastRMD.Count == 1) Metadata.LastRMD = lstLastRMD[0]; - if(lstPRI.Count == 1) Metadata.PRI = lstPRI[0]; - if(lstMediaID.Count == 1) Metadata.MediaID = lstMediaID[0]; - if(lstPFIR.Count == 1) Metadata.PFIR = lstPFIR[0]; - if(lstDCB.Count == 1) Metadata.DCB = lstDCB[0]; - if(lstDI.Count == 1) Metadata.DI = lstDI[0]; - if(lstPAC.Count == 1) Metadata.PAC = lstPAC[0]; - if(lstTOC.Count == 1) Metadata.TOC = lstTOC[0]; - if(lstCDText.Count == 1) Metadata.LeadInCdText = lstCDText[0]; + if(lstPFI.Count == 1) + Metadata.PFI = lstPFI[0]; - if(lstLeadIns.Count == 1) Metadata.LeadIn = lstLeadIns.ToArray(); - if(lstLeadOuts.Count == 1) Metadata.LeadOut = lstLeadOuts.ToArray(); + if(lstDMI.Count == 1) + Metadata.DMI = lstDMI[0]; - if(!string.IsNullOrWhiteSpace(txtPS3Key.Text) && !string.IsNullOrWhiteSpace(txtPS3Serial.Text)) - Metadata.PS3Encryption = new PS3EncryptionType {Key = txtPS3Key.Text, Serial = txtPS3Serial.Text}; + if(lstCMI.Count == 1) + Metadata.CMI = lstCMI[0]; + + if(lstBCA.Count == 1) + Metadata.BCA = lstBCA[0]; + + if(lstATIP.Count == 1) + Metadata.ATIP = lstATIP[0]; + + if(lstADIP.Count == 1) + Metadata.ADIP = lstADIP[0]; + + if(lstPMA.Count == 1) + Metadata.PMA = lstPMA[0]; + + if(lstDDS.Count == 1) + Metadata.DDS = lstDDS[0]; + + if(lstSAI.Count == 1) + Metadata.SAI = lstSAI[0]; + + if(lstLastRMD.Count == 1) + Metadata.LastRMD = lstLastRMD[0]; + + if(lstPRI.Count == 1) + Metadata.PRI = lstPRI[0]; + + if(lstMediaID.Count == 1) + Metadata.MediaID = lstMediaID[0]; + + if(lstPFIR.Count == 1) + Metadata.PFIR = lstPFIR[0]; + + if(lstDCB.Count == 1) + Metadata.DCB = lstDCB[0]; + + if(lstDI.Count == 1) + Metadata.DI = lstDI[0]; + + if(lstPAC.Count == 1) + Metadata.PAC = lstPAC[0]; + + if(lstTOC.Count == 1) + Metadata.TOC = lstTOC[0]; + + if(lstCDText.Count == 1) + Metadata.LeadInCdText = lstCDText[0]; + + if(lstLeadIns.Count == 1) + Metadata.LeadIn = lstLeadIns.ToArray(); + + if(lstLeadOuts.Count == 1) + Metadata.LeadOut = lstLeadOuts.ToArray(); + + if(!string.IsNullOrWhiteSpace(txtPS3Key.Text) && + !string.IsNullOrWhiteSpace(txtPS3Serial.Text)) + Metadata.PS3Encryption = new PS3EncryptionType + { + Key = txtPS3Key.Text, + Serial = txtPS3Serial.Text + }; Metadata.Track = lstTracks.ToArray(); - if(chkDumpHardware.Checked.Value && lstDumpHw.Count >= 1) Metadata.DumpHardwareArray = lstDumpHw.ToArray(); + if(chkDumpHardware.Checked.Value && + lstDumpHw.Count >= 1) + Metadata.DumpHardwareArray = lstDumpHw.ToArray(); Modified = true; Close(); } - protected void OnBtnCancelClicked(object sender, EventArgs e) - { - Close(); - } + protected void OnBtnCancelClicked(object sender, EventArgs e) => Close(); protected void OnBtnCancelPartitionClicked(object sender, EventArgs e) { @@ -1824,153 +2169,153 @@ namespace apprepodbmgr.Eto #region XAML UI elements #pragma warning disable 0649 - TextBox txtImage; - TextBox txtFormat; - TextBox txtOffset; - TextBox txtSize; - TextBox txtWriteOffset; - TextBox txtMediaTracks; - TextBox txtMediaSessions; - TextBox txtCopyProtection; - TextBox txtDiscType; - TextBox txtDiscSubtype; - CheckBox chkSequence; - Label lblDiscTitle; - TextBox txtDiscTitle; - Label lblSequence; - NumericUpDown spSequence; - Label lblTotalMedia; - NumericUpDown spTotalMedia; - Label lblSide; - NumericUpDown spSide; - Label lblLayer; - NumericUpDown spLayer; - CheckBox chkDimensions; - CheckBox chkRound; - StackLayout stkDiameter; - NumericUpDown spDiameter; - StackLayout stkHeight; - NumericUpDown spHeight; - StackLayout stkWidth; - NumericUpDown spWidth; - StackLayout stkThickness; - NumericUpDown spThickness; - CheckBox chkLayers; - StackLayout stkLayers; - EnumDropDown cmbLayerType; - GridView treeLayers; - NumericUpDown spNewLayer; - TextBox txtLayerSize; - GridView treeRingCodes; - NumericUpDown spRingCodeLayer; - TextBox txtRingCode; - GridView treeMasteringSIDs; - NumericUpDown spMasteringSIDLayer; - TextBox txtMasteringSID; - GridView treeToolstamps; - NumericUpDown spToolstampLayer; - TextBox txtToolstamp; - GridView treeMouldSIDs; - NumericUpDown spMouldSIDLayer; - TextBox txtMouldSID; - GridView treeMouldTexts; - NumericUpDown spMouldTextLayer; - TextBox txtMouldText; - GroupBox frmTOC; - GridView treeTOC; - GroupBox frmCDText; - GridView treeCDText; - GroupBox frmATIP; - GridView treeATIP; - GroupBox frmPMA; - GridView treePMA; - GroupBox frmLeadIns; - GridView treeLeadIn; - GroupBox frmLeadOuts; - GridView treeLeadOut; - GroupBox frmPFI; - GridView treePFI; - GroupBox frmDMI; - GridView treeDMI; - GroupBox frmCMI; - GridView treeCMI; - GroupBox frmBCA; - GridView treeBCA; - GroupBox frmDCB; - GridView treeDCB; - GroupBox frmPRI; - GridView treePRI; - GroupBox frmMediaID; - GridView treeMediaID; - GroupBox frmPFIR; - GridView treePFIR; - GroupBox frmLastRMD; - GridView treeLastRMD; - GroupBox frmADIP; - GridView treeADIP; - GroupBox frmDDS; - GridView treeDDS; - GroupBox frmSAI; - GridView treeSAI; - GroupBox frmDI; - GridView treeDI; - GroupBox frmPAC; - GridView treePAC; - TextBox txtPS3Key; - TextBox txtPS3Serial; - GridView treeTracks; - TextBox txtTrackStart; - TextBox txtTrackEnd; - TextBox txtMSFStart; - TextBox txtMSFEnd; - TextBox txtTrackSequence; - TextBox txtSessionSequence; - ComboBox cmbTrackType; - TextBox txtBytesPerSector; - TextBox txtAcoustID; - GridView treePartitions; - Button btnCancelPartition; - Button btnRemovePartition; - Button btnEditPartition; - Button btnApplyPartition; - Button btnAddPartition; - NumericUpDown spPartitionSequence; - TextBox txtPartitionStart; - TextBox txtPartitionEnd; - TextBox txtPartitionType; - StackLayout stkPartitionFields1; - StackLayout stkPartitionFields2; - TextBox txtPartitionName; - TextBox txtPartitionDescription; - GroupBox frmFilesystems; - GridView treeFilesystems; - Button btnCancelTrack; - Button btnApplyTrack; - Button btnEditTrack; - CheckBox chkDumpHardware; - GridView treeDumpHardware; - Button btnCancelHardware; - Button btnRemoveHardware; - Button btnEditHardware; - Button btnApplyHardware; - Button btnAddHardware; - GroupBox frmHardware; - TextBox txtHWManufacturer; - TextBox txtHWModel; - TextBox txtHWRevision; - TextBox txtHWFirmware; - TextBox txtHWSerial; - GridView treeExtents; - NumericUpDown spExtentStart; - NumericUpDown spExtentEnd; - TextBox txtDumpName; - TextBox txtDumpVersion; - TextBox txtDumpOS; - GroupBox frmLayers; - GroupBox frmPartitions; - StackLayout stkTrackFields1; - StackLayout stkTrackFields2; - StackLayout stkTrackFields3; + TextBox txtImage; + TextBox txtFormat; + TextBox txtOffset; + TextBox txtSize; + TextBox txtWriteOffset; + TextBox txtMediaTracks; + TextBox txtMediaSessions; + TextBox txtCopyProtection; + TextBox txtDiscType; + TextBox txtDiscSubtype; + CheckBox chkSequence; + Label lblDiscTitle; + TextBox txtDiscTitle; + Label lblSequence; + NumericUpDown spSequence; + Label lblTotalMedia; + NumericUpDown spTotalMedia; + Label lblSide; + NumericUpDown spSide; + Label lblLayer; + NumericUpDown spLayer; + CheckBox chkDimensions; + CheckBox chkRound; + StackLayout stkDiameter; + NumericUpDown spDiameter; + StackLayout stkHeight; + NumericUpDown spHeight; + StackLayout stkWidth; + NumericUpDown spWidth; + StackLayout stkThickness; + NumericUpDown spThickness; + CheckBox chkLayers; + StackLayout stkLayers; + readonly EnumDropDown cmbLayerType; + GridView treeLayers; + NumericUpDown spNewLayer; + TextBox txtLayerSize; + GridView treeRingCodes; + NumericUpDown spRingCodeLayer; + TextBox txtRingCode; + GridView treeMasteringSIDs; + NumericUpDown spMasteringSIDLayer; + TextBox txtMasteringSID; + GridView treeToolstamps; + NumericUpDown spToolstampLayer; + TextBox txtToolstamp; + GridView treeMouldSIDs; + NumericUpDown spMouldSIDLayer; + TextBox txtMouldSID; + GridView treeMouldTexts; + NumericUpDown spMouldTextLayer; + TextBox txtMouldText; + GroupBox frmTOC; + GridView treeTOC; + GroupBox frmCDText; + GridView treeCDText; + GroupBox frmATIP; + GridView treeATIP; + GroupBox frmPMA; + GridView treePMA; + GroupBox frmLeadIns; + GridView treeLeadIn; + GroupBox frmLeadOuts; + GridView treeLeadOut; + GroupBox frmPFI; + GridView treePFI; + GroupBox frmDMI; + GridView treeDMI; + GroupBox frmCMI; + GridView treeCMI; + GroupBox frmBCA; + GridView treeBCA; + GroupBox frmDCB; + GridView treeDCB; + GroupBox frmPRI; + GridView treePRI; + GroupBox frmMediaID; + GridView treeMediaID; + GroupBox frmPFIR; + GridView treePFIR; + GroupBox frmLastRMD; + GridView treeLastRMD; + GroupBox frmADIP; + GridView treeADIP; + GroupBox frmDDS; + GridView treeDDS; + GroupBox frmSAI; + GridView treeSAI; + GroupBox frmDI; + GridView treeDI; + GroupBox frmPAC; + GridView treePAC; + TextBox txtPS3Key; + TextBox txtPS3Serial; + GridView treeTracks; + TextBox txtTrackStart; + TextBox txtTrackEnd; + TextBox txtMSFStart; + TextBox txtMSFEnd; + TextBox txtTrackSequence; + TextBox txtSessionSequence; + ComboBox cmbTrackType; + TextBox txtBytesPerSector; + TextBox txtAcoustID; + GridView treePartitions; + Button btnCancelPartition; + Button btnRemovePartition; + Button btnEditPartition; + Button btnApplyPartition; + Button btnAddPartition; + NumericUpDown spPartitionSequence; + TextBox txtPartitionStart; + TextBox txtPartitionEnd; + TextBox txtPartitionType; + StackLayout stkPartitionFields1; + StackLayout stkPartitionFields2; + TextBox txtPartitionName; + TextBox txtPartitionDescription; + GroupBox frmFilesystems; + GridView treeFilesystems; + Button btnCancelTrack; + Button btnApplyTrack; + Button btnEditTrack; + CheckBox chkDumpHardware; + GridView treeDumpHardware; + Button btnCancelHardware; + Button btnRemoveHardware; + Button btnEditHardware; + Button btnApplyHardware; + Button btnAddHardware; + GroupBox frmHardware; + TextBox txtHWManufacturer; + TextBox txtHWModel; + TextBox txtHWRevision; + TextBox txtHWFirmware; + TextBox txtHWSerial; + GridView treeExtents; + NumericUpDown spExtentStart; + NumericUpDown spExtentEnd; + TextBox txtDumpName; + TextBox txtDumpVersion; + TextBox txtDumpOS; + GroupBox frmLayers; + GroupBox frmPartitions; + StackLayout stkTrackFields1; + StackLayout stkTrackFields2; + StackLayout stkTrackFields3; #pragma warning restore 0649 #endregion XAML UI elements } diff --git a/apprepodbmgr.Eto/dlgSettings.xeto.cs b/apprepodbmgr.Eto/dlgSettings.xeto.cs index c70c292..05964e0 100644 --- a/apprepodbmgr.Eto/dlgSettings.xeto.cs +++ b/apprepodbmgr.Eto/dlgSettings.xeto.cs @@ -47,7 +47,8 @@ namespace apprepodbmgr.Eto txtDatabase.Text = Settings.Current.DatabasePath; txtRepository.Text = Settings.Current.RepositoryPath; - if(!string.IsNullOrWhiteSpace(txtUnar.Text)) CheckUnar(); + if(!string.IsNullOrWhiteSpace(txtUnar.Text)) + CheckUnar(); cmbCompAlg = new EnumDropDown(); StackLayoutForAlgoEnum.Items.Add(new StackLayoutItem(cmbCompAlg, HorizontalAlignment.Stretch, true)); @@ -56,7 +57,9 @@ namespace apprepodbmgr.Eto spClamdPort.Value = 3310; chkAntivirus.Checked = Settings.Current.UseAntivirus; frmClamd.Visible = chkAntivirus.Checked.Value; - if(Settings.Current.UseAntivirus && Settings.Current.UseClamd) + + if(Settings.Current.UseAntivirus && + Settings.Current.UseClamd) { chkClamd.Checked = Settings.Current.UseClamd; txtClamdHost.Text = Settings.Current.ClamdHost; @@ -64,7 +67,9 @@ namespace apprepodbmgr.Eto chkClamdIsLocal.Checked = Settings.Current.ClamdIsLocal; } - if(!Settings.Current.UseAntivirus || !Settings.Current.UseVirusTotal) return; + if(!Settings.Current.UseAntivirus || + !Settings.Current.UseVirusTotal) + return; chkVirusTotal.Checked = true; chkVirusTotal.Enabled = true; @@ -73,10 +78,7 @@ namespace apprepodbmgr.Eto btnVirusTotal.Enabled = true; } - protected void OnBtnCancelClicked(object sender, EventArgs e) - { - Close(); - } + protected void OnBtnCancelClicked(object sender, EventArgs e) => Close(); protected void OnBtnApplyClicked(object sender, EventArgs e) { @@ -86,7 +88,9 @@ namespace apprepodbmgr.Eto Settings.Current.DatabasePath = txtDatabase.Text; Settings.Current.RepositoryPath = txtRepository.Text; Settings.Current.CompressionAlgorithm = cmbCompAlg.SelectedValue; - if(!chkClamd.Checked.Value || !chkAntivirus.Checked.Value) + + if(!chkClamd.Checked.Value || + !chkAntivirus.Checked.Value) { Settings.Current.UseClamd = false; Settings.Current.ClamdHost = null; @@ -94,7 +98,8 @@ namespace apprepodbmgr.Eto Settings.Current.ClamdIsLocal = false; } - if(chkVirusTotal.Checked.Value && chkAntivirus.Checked.Value) + if(chkVirusTotal.Checked.Value && + chkAntivirus.Checked.Value) { Settings.Current.UseVirusTotal = true; Settings.Current.VirusTotalKey = txtVirusTotal.Text; @@ -117,11 +122,17 @@ namespace apprepodbmgr.Eto protected void OnBtnUnarClicked(object sender, EventArgs e) { - OpenFileDialog dlgFile = new OpenFileDialog {Title = "Choose UnArchiver executable", MultiSelect = false}; + var dlgFile = new OpenFileDialog + { + Title = "Choose UnArchiver executable", + MultiSelect = false + }; + if(!string.IsNullOrWhiteSpace(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles))) dlgFile.Directory = new Uri(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)); - if(dlgFile.ShowDialog(this) != DialogResult.Ok) return; + if(dlgFile.ShowDialog(this) != DialogResult.Ok) + return; txtUnar.Text = dlgFile.FileName; lblUnarVersion.Visible = false; @@ -130,23 +141,31 @@ namespace apprepodbmgr.Eto protected void OnBtnTmpClicked(object sender, EventArgs e) { - SelectFolderDialog dlgFolder = - new SelectFolderDialog {Title = "Choose temporary folder", Directory = Path.GetTempPath()}; + var dlgFolder = new SelectFolderDialog + { + Title = "Choose temporary folder", + Directory = Path.GetTempPath() + }; - if(dlgFolder.ShowDialog(this) == DialogResult.Ok) txtTmp.Text = dlgFolder.Directory; + if(dlgFolder.ShowDialog(this) == DialogResult.Ok) + txtTmp.Text = dlgFolder.Directory; } protected void OnBtnRepositoryClicked(object sender, EventArgs e) { - SelectFolderDialog dlgFolder = - new SelectFolderDialog {Title = "Choose repository folder", Directory = Path.GetTempPath()}; + var dlgFolder = new SelectFolderDialog + { + Title = "Choose repository folder", + Directory = Path.GetTempPath() + }; - if(dlgFolder.ShowDialog(this) == DialogResult.Ok) txtRepository.Text = dlgFolder.Directory; + if(dlgFolder.ShowDialog(this) == DialogResult.Ok) + txtRepository.Text = dlgFolder.Directory; } protected void OnBtnDatabaseClicked(object sender, EventArgs e) { - SaveFileDialog dlgFile = new SaveFileDialog + var dlgFile = new SaveFileDialog { Title = "Choose database to open/create", Directory = new Uri(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)), @@ -154,20 +173,28 @@ namespace apprepodbmgr.Eto FileName = "apprepodbmgr.db" }; - if(dlgFile.ShowDialog(this) != DialogResult.Ok) return; + if(dlgFile.ShowDialog(this) != DialogResult.Ok) + return; if(File.Exists(dlgFile.FileName)) { DbCore dbCore = new SQLite(); bool notDb = false; - try { notDb |= !dbCore.OpenDb(dlgFile.FileName, null, null, null); } - catch { notDb = true; } + try + { + notDb |= !dbCore.OpenDb(dlgFile.FileName, null, null, null); + } + catch + { + notDb = true; + } if(notDb) { MessageBox.Show("Cannot open specified file as a database, please choose another.", MessageBoxType.Error); + return; } @@ -178,13 +205,20 @@ namespace apprepodbmgr.Eto DbCore dbCore = new SQLite(); bool notDb = false; - try { notDb |= !dbCore.CreateDb(dlgFile.FileName, null, null, null); } - catch { notDb = true; } + try + { + notDb |= !dbCore.CreateDb(dlgFile.FileName, null, null, null); + } + catch + { + notDb = true; + } if(notDb) { MessageBox.Show("Cannot create a database in the specified file as a database.", MessageBoxType.Error); + return; } @@ -201,35 +235,29 @@ namespace apprepodbmgr.Eto oldUnarPath = Settings.Current.UnArchiverPath; Settings.Current.UnArchiverPath = txtUnar.Text; - Thread thdCheckUnar = new Thread(Workers.CheckUnar); + var thdCheckUnar = new Thread(Workers.CheckUnar); thdCheckUnar.Start(); } - void CheckUnarFinished(string text) + void CheckUnarFinished(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - Workers.FinishedWithText -= CheckUnarFinished; - Workers.Failed -= CheckUnarFailed; + Workers.FinishedWithText -= CheckUnarFinished; + Workers.Failed -= CheckUnarFailed; - lblUnarVersion.Text = text; - lblUnarVersion.Visible = true; - Settings.Current.UnArchiverPath = oldUnarPath; - }); - } + lblUnarVersion.Text = text; + lblUnarVersion.Visible = true; + Settings.Current.UnArchiverPath = oldUnarPath; + }); - void CheckUnarFailed(string text) + void CheckUnarFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - Workers.FinishedWithText -= CheckUnarFinished; - Workers.Failed -= CheckUnarFailed; + Workers.FinishedWithText -= CheckUnarFinished; + Workers.Failed -= CheckUnarFailed; - txtUnar.Text = string.IsNullOrWhiteSpace(oldUnarPath) ? "" : oldUnarPath; - Settings.Current.UnArchiverPath = oldUnarPath; - MessageBox.Show(text, MessageBoxType.Error); - }); - } + txtUnar.Text = string.IsNullOrWhiteSpace(oldUnarPath) ? "" : oldUnarPath; + Settings.Current.UnArchiverPath = oldUnarPath; + MessageBox.Show(text, MessageBoxType.Error); + }); protected void OnChkAntivirusToggled(object sender, EventArgs e) { @@ -253,14 +281,15 @@ namespace apprepodbmgr.Eto if(string.IsNullOrEmpty(txtClamdHost.Text)) { MessageBox.Show("clamd host cannot be empty", MessageBoxType.Error); + return; } - string oldVersion = Context.ClamdVersion; + string oldVersion = Context.ClamdVersion; Context.ClamdVersion = null; - string oldHost = Settings.Current.ClamdHost; - ushort oldPort = Settings.Current.ClamdPort; + string oldHost = Settings.Current.ClamdHost; + ushort oldPort = Settings.Current.ClamdPort; Settings.Current.ClamdHost = txtClamdHost.Text; Settings.Current.ClamdPort = (ushort)spClamdPort.Value; @@ -272,6 +301,7 @@ namespace apprepodbmgr.Eto if(string.IsNullOrEmpty(Context.ClamdVersion)) { MessageBox.Show("Cannot connect to clamd", MessageBoxType.Error); + return; } @@ -290,39 +320,38 @@ namespace apprepodbmgr.Eto protected void OnBtnVirusTotalClicked(object sender, EventArgs e) { Workers.Failed += VirusTotalTestFailed; - if(!Workers.TestVirusTotal(txtVirusTotal.Text)) return; + + if(!Workers.TestVirusTotal(txtVirusTotal.Text)) + return; lblVirusTotal.Visible = true; lblVirusTotal.Text = "Working!"; } - static void VirusTotalTestFailed(string text) - { - MessageBox.Show(text, MessageBoxType.Error); - } + static void VirusTotalTestFailed(string text) => MessageBox.Show(text, MessageBoxType.Error); #region XAML UI elements #pragma warning disable 0649 - TextBox txtTmp; - TextBox txtUnar; - TextBox txtDatabase; - TextBox txtRepository; - Label lblUnarVersion; - EnumDropDown cmbCompAlg; - StackLayout StackLayoutForAlgoEnum; - GroupBox frmClamd; - CheckBox chkAntivirus; - CheckBox chkClamd; - TextBox txtClamdHost; - NumericUpDown spClamdPort; - Button btnClamdTest; - Label lblClamdVersion; - CheckBox chkClamdIsLocal; - GroupBox frmVirusTotal; - CheckBox chkVirusTotal; - TextBox txtVirusTotal; - Button btnVirusTotal; - Label lblVirusTotal; + TextBox txtTmp; + TextBox txtUnar; + TextBox txtDatabase; + TextBox txtRepository; + Label lblUnarVersion; + readonly EnumDropDown cmbCompAlg; + StackLayout StackLayoutForAlgoEnum; + GroupBox frmClamd; + CheckBox chkAntivirus; + CheckBox chkClamd; + TextBox txtClamdHost; + NumericUpDown spClamdPort; + Button btnClamdTest; + Label lblClamdVersion; + CheckBox chkClamdIsLocal; + GroupBox frmVirusTotal; + CheckBox chkVirusTotal; + TextBox txtVirusTotal; + Button btnVirusTotal; + Label lblVirusTotal; #pragma warning restore 0649 #endregion XAML UI elements } diff --git a/apprepodbmgr.Eto/frmMain.xeto.cs b/apprepodbmgr.Eto/frmMain.xeto.cs index d67446f..cd1450a 100644 --- a/apprepodbmgr.Eto/frmMain.xeto.cs +++ b/apprepodbmgr.Eto/frmMain.xeto.cs @@ -41,17 +41,17 @@ namespace apprepodbmgr.Eto { int infectedFiles; - ObservableCollection lstApps; - ObservableCollection lstFiles; - DbFile outIter; - bool populatingFiles; - bool scanningFiles; - Thread thdCleanFiles; - Thread thdCompressTo; - Thread thdPopulateApps; - Thread thdPopulateFiles; - Thread thdSaveAs; - Thread thdScanFile; + readonly ObservableCollection lstApps; + ObservableCollection lstFiles; + DbFile outIter; + bool populatingFiles; + bool scanningFiles; + Thread thdCleanFiles; + Thread thdCompressTo; + Thread thdPopulateApps; + Thread thdPopulateFiles; + Thread thdSaveAs; + Thread thdScanFile; public frmMain() { @@ -62,74 +62,130 @@ namespace apprepodbmgr.Eto lstApps = new ObservableCollection(); treeApps.DataStore = lstApps; + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.developer)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.developer) + }, HeaderText = "Developer" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.product)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.product) + }, HeaderText = "Product" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.version)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.version) + }, HeaderText = "Version" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.languages)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.languages) + }, HeaderText = "Languages" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.architecture)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.architecture) + }, HeaderText = "Architecture" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.targetos)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.targetos) + }, HeaderText = "Target OS" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.format)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.format) + }, HeaderText = "Format" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.description)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.description) + }, HeaderText = "Description" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.oem)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.oem) + }, HeaderText = "OEM?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.upgrade)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.upgrade) + }, HeaderText = "Upgrade?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.update)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.update) + }, HeaderText = "Update?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.source)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.source) + }, HeaderText = "Source?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.files)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.files) + }, HeaderText = "Files?" }); + treeApps.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.Installer)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.Installer) + }, HeaderText = "Installer?" }); @@ -138,11 +194,16 @@ namespace apprepodbmgr.Eto lstFiles = new ObservableCollection(); treeFiles.DataStore = lstFiles; + treeFiles.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.Sha256)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.Sha256) + }, HeaderText = "SHA256" }); + treeFiles.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -151,34 +212,45 @@ namespace apprepodbmgr.Eto }, HeaderText = "Length" }); + treeFiles.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.Crack)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.Crack) + }, HeaderText = "Crack?" }); + treeFiles.Columns.Add(new GridColumn { - DataCell = new CheckBoxCell {Binding = Binding.Property(r => r.HasVirus)}, + DataCell = new CheckBoxCell + { + Binding = Binding.Property(r => r.HasVirus) + }, HeaderText = "Has virus?" }); + treeFiles.Columns.Add(new GridColumn { DataCell = new TextBoxCell { - Binding = Binding.Property(r => r.ClamTime) - .Convert(s => s == null ? "Never" : s.Value.ToString()) + Binding = Binding.Property(r => r.ClamTime). + Convert(s => s == null ? "Never" : s.Value.ToString()) }, HeaderText = "Last scanned with clamd" }); + treeFiles.Columns.Add(new GridColumn { DataCell = new TextBoxCell { - Binding = Binding.Property(r => r.VirusTotalTime) - .Convert(s => s == null ? "Never" : s.Value.ToString()) + Binding = Binding.Property(r => r.VirusTotalTime). + Convert(s => s == null ? "Never" : s.Value.ToString()) }, HeaderText = "Last checked on VirusTotal" }); + treeFiles.Columns.Add(new GridColumn { DataCell = new TextBoxCell @@ -189,11 +261,13 @@ namespace apprepodbmgr.Eto }); treeFiles.AllowMultipleSelection = false; + treeFiles.CellFormatting += (sender, e) => { if(((DbFile)e.Item).HasVirus.HasValue) - e.BackgroundColor = ((DbFile)e.Item).HasVirus.Value ? Colors.Red : Colors.Green; - else e.BackgroundColor = Colors.Yellow; + e.BackgroundColor = ((DbFile)e.Item).HasVirus.Value ? Colors.Red : Colors.Green; + else + e.BackgroundColor = Colors.Yellow; e.ForegroundColor = Colors.Black; }; @@ -216,63 +290,64 @@ namespace apprepodbmgr.Eto thdPopulateApps.Start(); } - void LoadAppsFailed(string text) + void LoadAppsFailed(string text) => Application.Instance.Invoke(delegate { + MessageBox.Show($"Error {text} when populating applications, exiting...", MessageBoxButtons.OK, + MessageBoxType.Error, MessageBoxDefaultButton.OK); + + if(thdPopulateApps != null) + { + thdPopulateApps.Abort(); + thdPopulateApps = null; + } + + Workers.Failed -= LoadAppsFailed; + Workers.Finished -= LoadAppsFinished; + Workers.UpdateProgress -= UpdateProgress; + Application.Instance.Quit(); + }); + + void LoadAppsFinished() => Application.Instance.Invoke(delegate + { + Workers.Failed -= LoadAppsFailed; + Workers.Finished -= LoadAppsFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.AddApp -= AddApp; + + if(thdPopulateApps != null) + { + thdPopulateApps.Abort(); + thdPopulateApps = null; + } + + lblProgress.Visible = false; + prgProgress.Visible = false; + treeApps.Enabled = true; + btnAdd.Visible = true; + btnRemove.Visible = true; + btnCompress.Visible = Context.UsableDotNetZip; + btnSave.Visible = true; + btnSettings.Enabled = true; + lblAppStatus.Visible = true; + lblAppStatus.Text = $"{lstApps.Count} applications"; + }); + + void UpdateProgress(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { - MessageBox.Show($"Error {text} when populating applications, exiting...", MessageBoxButtons.OK, - MessageBoxType.Error, MessageBoxDefaultButton.OK); - if(thdPopulateApps != null) - { - thdPopulateApps.Abort(); - thdPopulateApps = null; - } + if(!string.IsNullOrWhiteSpace(text) && + !string.IsNullOrWhiteSpace(inner)) + lblProgress.Text = $"{text}: {inner}"; + else if(!string.IsNullOrWhiteSpace(inner)) + lblProgress.Text = inner; + else + lblProgress.Text = text; - Workers.Failed -= LoadAppsFailed; - Workers.Finished -= LoadAppsFinished; - Workers.UpdateProgress -= UpdateProgress; - Application.Instance.Quit(); - }); - } - - void LoadAppsFinished() - { - Application.Instance.Invoke(delegate - { - Workers.Failed -= LoadAppsFailed; - Workers.Finished -= LoadAppsFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.AddApp -= AddApp; - if(thdPopulateApps != null) - { - thdPopulateApps.Abort(); - thdPopulateApps = null; - } - - lblProgress.Visible = false; - prgProgress.Visible = false; - treeApps.Enabled = true; - btnAdd.Visible = true; - btnRemove.Visible = true; - btnCompress.Visible = Context.UsableDotNetZip; - btnSave.Visible = true; - btnSettings.Enabled = true; - lblAppStatus.Visible = true; - lblAppStatus.Text = $"{lstApps.Count} applications"; - }); - } - - void UpdateProgress(string text, string inner, long current, long maximum) - { - Application.Instance.Invoke(delegate - { - if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) - lblProgress.Text = $"{text}: {inner}"; - else if(!string.IsNullOrWhiteSpace(inner)) lblProgress.Text = inner; - else lblProgress.Text = text; if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -284,21 +359,26 @@ namespace apprepodbmgr.Eto prgProgress.MaxValue = (int)maximum; prgProgress.Value = (int)current; } - else prgProgress.Indeterminate = true; + else + prgProgress.Indeterminate = true; }); - } - void UpdateProgress2(string text, string inner, long current, long maximum) - { + void UpdateProgress2(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { - if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) - lblProgress2.Text = $"{text}: {inner}"; - else if(!string.IsNullOrWhiteSpace(inner)) lblProgress2.Text = inner; - else lblProgress2.Text = text; + if(!string.IsNullOrWhiteSpace(text) && + !string.IsNullOrWhiteSpace(inner)) + lblProgress2.Text = $"{text}: {inner}"; + else if(!string.IsNullOrWhiteSpace(inner)) + lblProgress2.Text = inner; + else + lblProgress2.Text = text; + if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -310,27 +390,35 @@ namespace apprepodbmgr.Eto prgProgress2.MaxValue = (int)maximum; prgProgress2.Value = (int)current; } - else prgProgress2.Indeterminate = true; + else + prgProgress2.Indeterminate = true; }); - } - void AddApp(DbEntry app) + void AddApp(DbEntry app) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate { lstApps.Add(new DBEntryForEto(app)); }); - } + lstApps.Add(new DBEntryForEto(app)); + }); protected void OnBtnAddClicked(object sender, EventArgs e) { - dlgAdd dlgAdd = new dlgAdd(); - dlgAdd.OnAddedApp += app => { lstApps.Add(new DBEntryForEto(app)); }; + var dlgAdd = new dlgAdd(); + + dlgAdd.OnAddedApp += app => + { + lstApps.Add(new DBEntryForEto(app)); + }; + dlgAdd.ShowModal(this); } protected void OnBtnRemoveClicked(object sender, EventArgs e) { - if(treeApps.SelectedItem == null) return; + if(treeApps.SelectedItem == null) + return; + if(MessageBox.Show("Are you sure you want to remove the selected application?", MessageBoxButtons.YesNo, - MessageBoxType.Question, MessageBoxDefaultButton.No) != DialogResult.Yes) return; + MessageBoxType.Question, MessageBoxDefaultButton.No) != DialogResult.Yes) + return; Workers.RemoveApp(((DBEntryForEto)treeApps.SelectedItem).id, ((DBEntryForEto)treeApps.SelectedItem).mdid); lstApps.Remove((DBEntryForEto)treeApps.SelectedItem); @@ -338,10 +426,16 @@ namespace apprepodbmgr.Eto protected void OnBtnSaveClicked(object sender, EventArgs e) { - if(treeApps.SelectedItem == null) return; + if(treeApps.SelectedItem == null) + return; - SelectFolderDialog dlgFolder = new SelectFolderDialog {Title = "Save to..."}; - if(dlgFolder.ShowDialog(this) != DialogResult.Ok) return; + var dlgFolder = new SelectFolderDialog + { + Title = "Save to..." + }; + + if(dlgFolder.ShowDialog(this) != DialogResult.Ok) + return; Context.DbInfo.Id = ((DBEntryForEto)treeApps.SelectedItem).id; Context.Path = dlgFolder.Directory; @@ -366,74 +460,68 @@ namespace apprepodbmgr.Eto thdSaveAs.Start(); } - void SaveAsFailed(string text) + void SaveAsFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + MessageBox.Show(text, MessageBoxButtons.OK, MessageBoxType.Error); + + lblProgress.Visible = false; + prgProgress.Visible = false; + lblProgress2.Visible = false; + prgProgress2.Visible = false; + treeApps.Enabled = true; + btnAdd.Visible = true; + btnRemove.Visible = true; + btnCompress.Visible = Context.UsableDotNetZip; + btnSave.Visible = true; + btnSettings.Enabled = true; + btnStop.Visible = false; + + Workers.Failed -= SaveAsFailed; + Workers.Finished -= SaveAsFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + + if(thdSaveAs != null) { - MessageBox.Show(text, MessageBoxButtons.OK, MessageBoxType.Error); + thdSaveAs.Abort(); + thdSaveAs = null; + } - lblProgress.Visible = false; - prgProgress.Visible = false; - lblProgress2.Visible = false; - prgProgress2.Visible = false; - treeApps.Enabled = true; - btnAdd.Visible = true; - btnRemove.Visible = true; - btnCompress.Visible = Context.UsableDotNetZip; - btnSave.Visible = true; - btnSettings.Enabled = true; - btnStop.Visible = false; + Context.Path = null; + }); - Workers.Failed -= SaveAsFailed; - Workers.Finished -= SaveAsFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; - - if(thdSaveAs != null) - { - thdSaveAs.Abort(); - thdSaveAs = null; - } - - Context.Path = null; - }); - } - - void SaveAsFinished() + void SaveAsFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + lblProgress.Visible = false; + prgProgress.Visible = false; + lblProgress2.Visible = false; + prgProgress2.Visible = false; + treeApps.Enabled = true; + btnAdd.Visible = true; + btnRemove.Visible = true; + btnCompress.Visible = Context.UsableDotNetZip; + btnSave.Visible = true; + btnSettings.Enabled = true; + btnStop.Visible = false; + + Workers.Failed -= SaveAsFailed; + Workers.Finished -= SaveAsFinished; + Workers.UpdateProgress -= UpdateProgress; + + if(thdSaveAs != null) { - lblProgress.Visible = false; - prgProgress.Visible = false; - lblProgress2.Visible = false; - prgProgress2.Visible = false; - treeApps.Enabled = true; - btnAdd.Visible = true; - btnRemove.Visible = true; - btnCompress.Visible = Context.UsableDotNetZip; - btnSave.Visible = true; - btnSettings.Enabled = true; - btnStop.Visible = false; + thdSaveAs.Abort(); + thdSaveAs = null; + } - Workers.Failed -= SaveAsFailed; - Workers.Finished -= SaveAsFinished; - Workers.UpdateProgress -= UpdateProgress; + MessageBox.Show($"Correctly saved to {Context.Path}"); - if(thdSaveAs != null) - { - thdSaveAs.Abort(); - thdSaveAs = null; - } - - MessageBox.Show($"Correctly saved to {Context.Path}"); - - Context.Path = null; - }); - } + Context.Path = null; + }); protected void OnBtnSettingsClicked(object sender, EventArgs e) { - dlgSettings _dlgSettings = new dlgSettings(); + var _dlgSettings = new dlgSettings(); _dlgSettings.ShowModal(); } @@ -467,24 +555,27 @@ namespace apprepodbmgr.Eto thdPopulateApps = null; } - if(thdSaveAs == null) return; + if(thdSaveAs == null) + return; thdSaveAs.Abort(); thdSaveAs = null; } - protected void OnDeleteEvent(object sender, EventArgs e) - { - OnBtnStopClicked(sender, e); - } + protected void OnDeleteEvent(object sender, EventArgs e) => OnBtnStopClicked(sender, e); protected void OnBtnCompressClicked(object sender, EventArgs e) { - if(treeApps.SelectedItem == null) return; + if(treeApps.SelectedItem == null) + return; - SaveFileDialog dlgFile = new SaveFileDialog {Title = "Compress to..."}; + var dlgFile = new SaveFileDialog + { + Title = "Compress to..." + }; - if(dlgFile.ShowDialog(this) != DialogResult.Ok) return; + if(dlgFile.ShowDialog(this) != DialogResult.Ok) + return; Context.DbInfo.Id = ((DBEntryForEto)treeApps.SelectedItem).id; Context.Path = dlgFile.FileName; @@ -509,70 +600,64 @@ namespace apprepodbmgr.Eto thdCompressTo.Start(); } - void CompressToFailed(string text) + void CompressToFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + MessageBox.Show(text, MessageBoxButtons.OK, MessageBoxType.Error); + lblProgress.Visible = false; + lblProgress2.Visible = false; + prgProgress.Visible = false; + prgProgress2.Visible = false; + treeApps.Enabled = true; + btnAdd.Visible = true; + btnRemove.Visible = true; + btnCompress.Visible = Context.UsableDotNetZip; + btnSave.Visible = true; + btnSettings.Enabled = true; + btnStop.Visible = false; + + Workers.Failed -= CompressToFailed; + Workers.Finished -= CompressToFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + + if(thdCompressTo != null) { - MessageBox.Show(text, MessageBoxButtons.OK, MessageBoxType.Error); - lblProgress.Visible = false; - lblProgress2.Visible = false; - prgProgress.Visible = false; - prgProgress2.Visible = false; - treeApps.Enabled = true; - btnAdd.Visible = true; - btnRemove.Visible = true; - btnCompress.Visible = Context.UsableDotNetZip; - btnSave.Visible = true; - btnSettings.Enabled = true; - btnStop.Visible = false; + thdCompressTo.Abort(); + thdCompressTo = null; + } - Workers.Failed -= CompressToFailed; - Workers.Finished -= CompressToFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; + Context.Path = null; + }); - if(thdCompressTo != null) - { - thdCompressTo.Abort(); - thdCompressTo = null; - } - - Context.Path = null; - }); - } - - void CompressToFinished() + void CompressToFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + lblProgress.Visible = false; + lblProgress2.Visible = false; + prgProgress.Visible = false; + prgProgress2.Visible = false; + treeApps.Enabled = true; + btnAdd.Visible = true; + btnRemove.Visible = true; + btnCompress.Visible = Context.UsableDotNetZip; + btnSave.Visible = true; + btnSettings.Enabled = true; + btnStop.Visible = false; + + Workers.Failed -= CompressToFailed; + Workers.Finished -= CompressToFinished; + Workers.UpdateProgress -= UpdateProgress; + Workers.UpdateProgress2 -= UpdateProgress2; + + if(thdCompressTo != null) { - lblProgress.Visible = false; - lblProgress2.Visible = false; - prgProgress.Visible = false; - prgProgress2.Visible = false; - treeApps.Enabled = true; - btnAdd.Visible = true; - btnRemove.Visible = true; - btnCompress.Visible = Context.UsableDotNetZip; - btnSave.Visible = true; - btnSettings.Enabled = true; - btnStop.Visible = false; + thdCompressTo.Abort(); + thdCompressTo = null; + } - Workers.Failed -= CompressToFailed; - Workers.Finished -= CompressToFinished; - Workers.UpdateProgress -= UpdateProgress; - Workers.UpdateProgress2 -= UpdateProgress2; + MessageBox.Show($"Correctly compressed as {Context.Path}"); - if(thdCompressTo != null) - { - thdCompressTo.Abort(); - thdCompressTo = null; - } - - MessageBox.Show($"Correctly compressed as {Context.Path}"); - - Context.Path = null; - }); - } + Context.Path = null; + }); protected void OnBtnStopFilesClicked(object sender, EventArgs e) { @@ -607,10 +692,11 @@ namespace apprepodbmgr.Eto protected void OnBtnToggleCrackClicked(object sender, EventArgs e) { - if(treeFiles.SelectedItem == null) return; + if(treeFiles.SelectedItem == null) + return; - DbFile file = (DbFile)treeFiles.SelectedItem; - bool crack = !file.Crack; + var file = (DbFile)treeFiles.SelectedItem; + bool crack = !file.Crack; Workers.ToggleCrack(file.Sha256, crack); @@ -621,7 +707,8 @@ namespace apprepodbmgr.Eto protected void OnBtnScanWithClamdClicked(object sender, EventArgs e) { - if(treeFiles.SelectedItem == null) return; + if(treeFiles.SelectedItem == null) + return; DbFile file = Workers.GetDBFile(((DbFile)treeFiles.SelectedItem).Sha256); outIter = (DbFile)treeFiles.SelectedItem; @@ -629,6 +716,7 @@ namespace apprepodbmgr.Eto if(file == null) { MessageBox.Show("Cannot get file from database", MessageBoxType.Error); + return; } @@ -649,57 +737,57 @@ namespace apprepodbmgr.Eto thdScanFile.Start(); } - void ClamdFailed(string text) + void ClamdFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - treeFiles.Enabled = true; - btnToggleCrack.Enabled = true; - btnScanWithClamd.Enabled = true; - btnCheckInVirusTotal.Enabled = true; - prgProgressFiles1.Visible = false; - lblProgressFiles1.Visible = false; - Workers.Failed -= ClamdFailed; - Workers.ScanFinished -= ClamdFinished; - Workers.UpdateProgress -= UpdateVirusProgress; - lblProgressFiles1.Text = ""; - if(thdScanFile == null) return; + treeFiles.Enabled = true; + btnToggleCrack.Enabled = true; + btnScanWithClamd.Enabled = true; + btnCheckInVirusTotal.Enabled = true; + prgProgressFiles1.Visible = false; + lblProgressFiles1.Visible = false; + Workers.Failed -= ClamdFailed; + Workers.ScanFinished -= ClamdFinished; + Workers.UpdateProgress -= UpdateVirusProgress; + lblProgressFiles1.Text = ""; - thdScanFile.Abort(); + if(thdScanFile == null) + return; + + thdScanFile.Abort(); + thdScanFile = null; + }); + + void ClamdFinished(DbFile file) => Application.Instance.Invoke(delegate + { + treeFiles.Enabled = true; + btnToggleCrack.Enabled = true; + btnScanWithClamd.Enabled = true; + btnCheckInVirusTotal.Enabled = true; + Workers.Failed -= ClamdFailed; + Workers.ScanFinished -= ClamdFinished; + Workers.UpdateProgress -= UpdateVirusProgress; + lblProgressFiles1.Text = ""; + prgProgressFiles1.Visible = false; + lblProgressFiles1.Visible = false; + + if(thdScanFile != null) thdScanFile = null; - }); - } - void ClamdFinished(DbFile file) - { - Application.Instance.Invoke(delegate - { - treeFiles.Enabled = true; - btnToggleCrack.Enabled = true; - btnScanWithClamd.Enabled = true; - btnCheckInVirusTotal.Enabled = true; - Workers.Failed -= ClamdFailed; - Workers.ScanFinished -= ClamdFinished; - Workers.UpdateProgress -= UpdateVirusProgress; - lblProgressFiles1.Text = ""; - prgProgressFiles1.Visible = false; - lblProgressFiles1.Visible = false; - if(thdScanFile != null) thdScanFile = null; + if((!outIter.HasVirus.HasValue || (outIter.HasVirus.HasValue && !outIter.HasVirus.Value)) && + file.HasVirus.HasValue && + file.HasVirus.Value) + infectedFiles++; - if((!outIter.HasVirus.HasValue || outIter.HasVirus.HasValue && !outIter.HasVirus.Value) && - file.HasVirus.HasValue && - file.HasVirus.Value) infectedFiles++; + lstFiles.Remove(outIter); + AddFile(file); - lstFiles.Remove(outIter); - AddFile(file); - - lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)"; - }); - } + lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)"; + }); protected void OnBtnCheckInVirusTotalClicked(object sender, EventArgs e) { - if(treeFiles.SelectedItem == null) return; + if(treeFiles.SelectedItem == null) + return; DbFile file = Workers.GetDBFile(((DbFile)treeFiles.SelectedItem).Sha256); outIter = (DbFile)treeFiles.SelectedItem; @@ -707,6 +795,7 @@ namespace apprepodbmgr.Eto if(file == null) { MessageBox.Show("Cannot get file from database", MessageBoxType.Error); + return; } @@ -727,54 +816,55 @@ namespace apprepodbmgr.Eto thdScanFile.Start(); } - void VirusTotalFailed(string text) + void VirusTotalFailed(string text) => Application.Instance.Invoke(delegate { + treeFiles.Enabled = true; + btnToggleCrack.Enabled = true; + btnScanWithClamd.Enabled = true; + btnCheckInVirusTotal.Enabled = true; + prgProgressFiles1.Visible = false; + Workers.Failed -= VirusTotalFailed; + Workers.ScanFinished -= VirusTotalFinished; + Workers.UpdateProgress -= UpdateVirusProgress; + lblProgressFiles1.Text = ""; + + if(thdScanFile != null) + thdScanFile = null; + + MessageBox.Show(text, MessageBoxType.Error); + }); + + void VirusTotalFinished(DbFile file) => Application.Instance.Invoke(delegate + { + treeFiles.Enabled = true; + btnToggleCrack.Enabled = true; + btnScanWithClamd.Enabled = true; + btnCheckInVirusTotal.Enabled = true; + Workers.Failed -= VirusTotalFailed; + Workers.ScanFinished -= VirusTotalFinished; + Workers.UpdateProgress -= UpdateVirusProgress; + lblProgressFiles1.Text = ""; + prgProgressFiles1.Visible = false; + + if(thdScanFile != null) + thdScanFile = null; + + if((!outIter.HasVirus.HasValue || (outIter.HasVirus.HasValue && !outIter.HasVirus.Value)) && + file.HasVirus.HasValue && + file.HasVirus.Value) + infectedFiles++; + + lstFiles.Remove(outIter); + AddFile(file); + + lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)"; + }); + + void UpdateVirusProgress(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { - treeFiles.Enabled = true; - btnToggleCrack.Enabled = true; - btnScanWithClamd.Enabled = true; - btnCheckInVirusTotal.Enabled = true; - prgProgressFiles1.Visible = false; - Workers.Failed -= VirusTotalFailed; - Workers.ScanFinished -= VirusTotalFinished; - Workers.UpdateProgress -= UpdateVirusProgress; - lblProgressFiles1.Text = ""; - if(thdScanFile != null) thdScanFile = null; - MessageBox.Show(text, MessageBoxType.Error); + lblProgressFiles1.Text = text; }); - } - - void VirusTotalFinished(DbFile file) - { - Application.Instance.Invoke(delegate - { - treeFiles.Enabled = true; - btnToggleCrack.Enabled = true; - btnScanWithClamd.Enabled = true; - btnCheckInVirusTotal.Enabled = true; - Workers.Failed -= VirusTotalFailed; - Workers.ScanFinished -= VirusTotalFinished; - Workers.UpdateProgress -= UpdateVirusProgress; - lblProgressFiles1.Text = ""; - prgProgressFiles1.Visible = false; - if(thdScanFile != null) thdScanFile = null; - - if((!outIter.HasVirus.HasValue || outIter.HasVirus.HasValue && !outIter.HasVirus.Value) && - file.HasVirus.HasValue && - file.HasVirus.Value) infectedFiles++; - - lstFiles.Remove(outIter); - AddFile(file); - - lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)"; - }); - } - - void UpdateVirusProgress(string text, string inner, long current, long maximum) - { - Application.Instance.Invoke(delegate { lblProgressFiles1.Text = text; }); - } protected void OnBtnPopulateFilesClicked(object sender, EventArgs e) { @@ -798,17 +888,22 @@ namespace apprepodbmgr.Eto thdPopulateFiles.Start(); } - void UpdateFileProgress(string text, string inner, long current, long maximum) - { + void UpdateFileProgress(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { - if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) - lblProgressFiles1.Text = $"{text}: {inner}"; - else if(!string.IsNullOrWhiteSpace(inner)) lblProgressFiles1.Text = inner; - else lblProgressFiles1.Text = text; + if(!string.IsNullOrWhiteSpace(text) && + !string.IsNullOrWhiteSpace(inner)) + lblProgressFiles1.Text = $"{text}: {inner}"; + else if(!string.IsNullOrWhiteSpace(inner)) + lblProgressFiles1.Text = inner; + else + lblProgressFiles1.Text = text; + if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -820,21 +915,26 @@ namespace apprepodbmgr.Eto prgProgressFiles1.MaxValue = (int)maximum; prgProgressFiles1.Value = (int)current; } - else prgProgressFiles1.Indeterminate = true; + else + prgProgressFiles1.Indeterminate = true; }); - } - void UpdateFileProgress2(string text, string inner, long current, long maximum) - { + void UpdateFileProgress2(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { - if(!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(inner)) - lblProgressFiles2.Text = $"{text}: {inner}"; - else if(!string.IsNullOrWhiteSpace(inner)) lblProgressFiles2.Text = inner; - else lblProgressFiles2.Text = text; + if(!string.IsNullOrWhiteSpace(text) && + !string.IsNullOrWhiteSpace(inner)) + lblProgressFiles2.Text = $"{text}: {inner}"; + else if(!string.IsNullOrWhiteSpace(inner)) + lblProgressFiles2.Text = inner; + else + lblProgressFiles2.Text = text; + if(maximum > 0) { - if(current < int.MinValue || current > int.MaxValue || maximum < int.MinValue || + if(current < int.MinValue || + current > int.MaxValue || + maximum < int.MinValue || maximum > int.MaxValue) { current /= 100; @@ -846,93 +946,87 @@ namespace apprepodbmgr.Eto prgProgressFiles2.MaxValue = (int)maximum; prgProgressFiles2.Value = (int)current; } - else prgProgressFiles2.Indeterminate = true; + else + prgProgressFiles2.Indeterminate = true; }); - } - void AddFile(DbFile file) + void AddFile(DbFile file) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - if(file.HasVirus.HasValue && file.HasVirus.Value) infectedFiles++; + if(file.HasVirus.HasValue && + file.HasVirus.Value) + infectedFiles++; - lstFiles.Add(file); - }); - } + lstFiles.Add(file); + }); - void AddFiles(List files) + void AddFiles(List files) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - List foo = new List(); - foo.AddRange(lstFiles); - foo.AddRange(files); - lstFiles = new ObservableCollection(foo); + List foo = new List(); + foo.AddRange(lstFiles); + foo.AddRange(files); + lstFiles = new ObservableCollection(foo); - foreach(DbFile file in files) - if(file.HasVirus.HasValue && file.HasVirus.Value) - infectedFiles++; - }); - } + foreach(DbFile file in files) + if(file.HasVirus.HasValue && + file.HasVirus.Value) + infectedFiles++; + }); - void LoadFilesFailed(string text) + void LoadFilesFailed(string text) => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate + MessageBox.Show($"Error {text} when populating files, exiting...", MessageBoxType.Error); + Workers.Failed -= LoadFilesFailed; + Workers.Finished -= LoadFilesFinished; + Workers.UpdateProgress -= UpdateFileProgress2; + + if(thdPopulateFiles != null) { - MessageBox.Show($"Error {text} when populating files, exiting...", MessageBoxType.Error); - Workers.Failed -= LoadFilesFailed; - Workers.Finished -= LoadFilesFinished; - Workers.UpdateProgress -= UpdateFileProgress2; - if(thdPopulateFiles != null) - { - thdPopulateFiles.Abort(); - thdPopulateFiles = null; - } + thdPopulateFiles.Abort(); + thdPopulateFiles = null; + } - tabApps.Enabled = true; - lstFiles.Clear(); - btnStopFiles.Visible = false; - btnPopulateFiles.Visible = true; - populatingFiles = false; - }); - } + tabApps.Enabled = true; + lstFiles.Clear(); + btnStopFiles.Visible = false; + btnPopulateFiles.Visible = true; + populatingFiles = false; + }); - void LoadFilesFinished() + void LoadFilesFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - Workers.Failed -= LoadFilesFailed; - Workers.Finished -= LoadFilesFinished; - Workers.UpdateProgress -= UpdateFileProgress2; - if(thdPopulateFiles != null) - { - thdPopulateFiles.Abort(); - thdPopulateFiles = null; - } + Workers.Failed -= LoadFilesFailed; + Workers.Finished -= LoadFilesFinished; + Workers.UpdateProgress -= UpdateFileProgress2; - treeFiles.DataStore = lstFiles; - lblProgressFiles1.Visible = false; - lblProgressFiles2.Visible = false; - prgProgressFiles1.Visible = false; - prgProgressFiles2.Visible = false; - btnToggleCrack.Visible = true; - btnScanWithClamd.Visible = true; - btnCheckInVirusTotal.Visible = true; - btnStopFiles.Visible = false; - btnPopulateFiles.Visible = false; - populatingFiles = false; - treeFiles.Enabled = true; - tabApps.Enabled = true; - btnScanAllPending.Visible = true; - btnCleanFiles.Visible = true; - lblFileStatus.Visible = true; - lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)"; - }); - } + if(thdPopulateFiles != null) + { + thdPopulateFiles.Abort(); + thdPopulateFiles = null; + } + + treeFiles.DataStore = lstFiles; + lblProgressFiles1.Visible = false; + lblProgressFiles2.Visible = false; + prgProgressFiles1.Visible = false; + prgProgressFiles2.Visible = false; + btnToggleCrack.Visible = true; + btnScanWithClamd.Visible = true; + btnCheckInVirusTotal.Visible = true; + btnStopFiles.Visible = false; + btnPopulateFiles.Visible = false; + populatingFiles = false; + treeFiles.Enabled = true; + tabApps.Enabled = true; + btnScanAllPending.Visible = true; + btnCleanFiles.Visible = true; + lblFileStatus.Visible = true; + lblFileStatus.Text = $"{lstFiles.Count} files ({infectedFiles} infected)"; + }); void treeFilesSelectionChanged(object sender, EventArgs e) { - if(treeFiles.SelectedItem == null) return; + if(treeFiles.SelectedItem == null) + return; btnToggleCrack.Text = ((DbFile)treeFiles.SelectedItem).Crack ? "Mark as not crack" : "Mark as crack"; } @@ -961,41 +1055,43 @@ namespace apprepodbmgr.Eto thdScanFile.Start(); } - void AllClamdFinished() + void AllClamdFinished() => Application.Instance.Invoke(delegate { + treeFiles.Enabled = true; + btnToggleCrack.Enabled = true; + btnScanWithClamd.Enabled = true; + btnCheckInVirusTotal.Enabled = true; + btnScanAllPending.Enabled = true; + Workers.Finished -= AllClamdFinished; + Workers.UpdateProgress -= UpdateVirusProgress2; + Workers.UpdateProgress2 -= UpdateFileProgress; + lblProgressFiles1.Text = ""; + prgProgressFiles1.Visible = false; + lblProgressFiles2.Text = ""; + prgProgressFiles2.Visible = false; + btnStopFiles.Visible = false; + scanningFiles = false; + + if(thdScanFile != null) + thdScanFile = null; + + OnBtnPopulateFilesClicked(null, new EventArgs()); + }); + + void UpdateVirusProgress2(string text, string inner, long current, long maximum) => Application.Instance.Invoke(delegate { - treeFiles.Enabled = true; - btnToggleCrack.Enabled = true; - btnScanWithClamd.Enabled = true; - btnCheckInVirusTotal.Enabled = true; - btnScanAllPending.Enabled = true; - Workers.Finished -= AllClamdFinished; - Workers.UpdateProgress -= UpdateVirusProgress2; - Workers.UpdateProgress2 -= UpdateFileProgress; - lblProgressFiles1.Text = ""; - prgProgressFiles1.Visible = false; - lblProgressFiles2.Text = ""; - prgProgressFiles2.Visible = false; - btnStopFiles.Visible = false; - scanningFiles = false; - if(thdScanFile != null) thdScanFile = null; - - OnBtnPopulateFilesClicked(null, new EventArgs()); + lblProgressFiles2.Text = text; }); - } - - void UpdateVirusProgress2(string text, string inner, long current, long maximum) - { - Application.Instance.Invoke(delegate { lblProgressFiles2.Text = text; }); - } protected void OnBtnCleanFilesClicked(object sender, EventArgs e) { DialogResult result = MessageBox.Show("This option will search the database for any known file that doesn't\n" + "belong to any application and remove it from the database.\n\n" + "It will then search the repository for any file not on the database and remove it.\n\n" + "THIS OPERATION MAY VERY LONG, CANNOT BE CANCELED AND REMOVES DATA ON DISK.\n\n" + "Are you sure to continue?", MessageBoxButtons.YesNo, MessageBoxType.Question); - if(result != DialogResult.Yes) return; + + if(result != DialogResult.Yes) + return; btnCleanFiles.Visible = false; btnToggleCrack.Visible = false; @@ -1023,33 +1119,32 @@ namespace apprepodbmgr.Eto thdCleanFiles.Start(); } - void CleanFilesFinished() + void CleanFilesFinished() => Application.Instance.Invoke(delegate { - Application.Instance.Invoke(delegate - { - btnCleanFiles.Visible = true; - btnToggleCrack.Visible = true; - btnScanWithClamd.Visible = true; - btnScanAllPending.Visible = true; - btnCheckInVirusTotal.Visible = true; - tabApps.Enabled = true; - treeFiles.Enabled = true; - Workers.Finished -= CleanFilesFinished; - Workers.UpdateProgress -= UpdateFileProgress; - Workers.UpdateProgress2 -= UpdateFileProgress2; - lblProgressFiles1.Text = ""; - prgProgressFiles1.Visible = false; - lblProgressFiles2.Text = ""; - prgProgressFiles2.Visible = false; - btnSettings.Enabled = true; - mnuCompress.Enabled = true; - btnQuit.Enabled = true; - mnuFile.Enabled = true; - if(thdCleanFiles != null) thdCleanFiles = null; + btnCleanFiles.Visible = true; + btnToggleCrack.Visible = true; + btnScanWithClamd.Visible = true; + btnScanAllPending.Visible = true; + btnCheckInVirusTotal.Visible = true; + tabApps.Enabled = true; + treeFiles.Enabled = true; + Workers.Finished -= CleanFilesFinished; + Workers.UpdateProgress -= UpdateFileProgress; + Workers.UpdateProgress2 -= UpdateFileProgress2; + lblProgressFiles1.Text = ""; + prgProgressFiles1.Visible = false; + lblProgressFiles2.Text = ""; + prgProgressFiles2.Visible = false; + btnSettings.Enabled = true; + mnuCompress.Enabled = true; + btnQuit.Enabled = true; + mnuFile.Enabled = true; - OnBtnPopulateFilesClicked(null, new EventArgs()); - }); - } + if(thdCleanFiles != null) + thdCleanFiles = null; + + OnBtnPopulateFilesClicked(null, new EventArgs()); + }); #region XAML UI elements #pragma warning disable 0649 diff --git a/apprepodbmgr.Eto/pnlDescription.xeto.cs b/apprepodbmgr.Eto/pnlDescription.xeto.cs index 66fb051..1d03a50 100644 --- a/apprepodbmgr.Eto/pnlDescription.xeto.cs +++ b/apprepodbmgr.Eto/pnlDescription.xeto.cs @@ -11,9 +11,9 @@ namespace apprepodbmgr.Eto { public class pnlDescription : Panel { - ObservableCollection cmbCodepagesItems; - Encoding currentEncoding; - public string description; + readonly ObservableCollection cmbCodepagesItems; + Encoding currentEncoding; + public string description; public pnlDescription() { @@ -21,31 +21,52 @@ namespace apprepodbmgr.Eto treeFiles.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r) + }, HeaderText = "File" }); treeFiles.AllowMultipleSelection = false; treeFiles.SelectionChanged += TreeFilesOnSelectionChanged; cmbCodepagesItems = new ObservableCollection(); + foreach(EncodingInfo enc in Claunia.Encoding.Encoding.GetEncodings()) - cmbCodepagesItems.Add(new ListItem {Key = enc.Name, Text = enc.DisplayName}); + cmbCodepagesItems.Add(new ListItem + { + Key = enc.Name, + Text = enc.DisplayName + }); + foreach(System.Text.EncodingInfo enc in Encoding.GetEncodings()) - cmbCodepagesItems.Add(new ListItem {Key = enc.Name, Text = enc.GetEncoding().EncodingName}); + cmbCodepagesItems.Add(new ListItem + { + Key = enc.Name, + Text = enc.GetEncoding().EncodingName + }); + cmbCodepages.DataStore = cmbCodepagesItems.OrderBy(t => t.Text); + try { currentEncoding = Claunia.Encoding.Encoding.GetEncoding("ibm437"); cmbCodepages.SelectedKey = currentEncoding.BodyName; } - catch { currentEncoding = Encoding.ASCII; } + catch + { + currentEncoding = Encoding.ASCII; + } cmbCodepages.SelectedIndexChanged += CmbCodepagesOnSelectedIndexChanged; } void CmbCodepagesOnSelectedIndexChanged(object sender, EventArgs eventArgs) { - try { currentEncoding = Claunia.Encoding.Encoding.GetEncoding(cmbCodepages.SelectedKey); } + try + { + currentEncoding = Claunia.Encoding.Encoding.GetEncoding(cmbCodepages.SelectedKey); + } catch { currentEncoding = Encoding.ASCII; @@ -59,9 +80,11 @@ namespace apprepodbmgr.Eto { txtDescription.Text = ""; description = null; - if(!(treeFiles.SelectedItem is string file)) return; - StreamReader sr = new StreamReader(file, currentEncoding); + if(!(treeFiles.SelectedItem is string file)) + return; + + var sr = new StreamReader(file, currentEncoding); description = sr.ReadToEnd(); txtDescription.Text = description; sr.Close(); diff --git a/apprepodbmgr.Eto/pnlStrings.xeto.cs b/apprepodbmgr.Eto/pnlStrings.xeto.cs index 8bcf273..8f79279 100644 --- a/apprepodbmgr.Eto/pnlStrings.xeto.cs +++ b/apprepodbmgr.Eto/pnlStrings.xeto.cs @@ -12,9 +12,13 @@ namespace apprepodbmgr.Eto treeStrings.AllowMultipleSelection = false; treeStrings.ShowHeader = false; + treeStrings.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r) + }, HeaderText = "String" }); } @@ -22,7 +26,9 @@ namespace apprepodbmgr.Eto void OnBtnDeveloperClick(object sender, EventArgs eventArgs) { txtDeveloper.Text = ""; - if(!(treeStrings.SelectedItem is string str)) return; + + if(!(treeStrings.SelectedItem is string str)) + return; txtDeveloper.Text = str; } @@ -30,7 +36,9 @@ namespace apprepodbmgr.Eto void OnBtnPublisherClick(object sender, EventArgs eventArgs) { txtPublisher.Text = ""; - if(!(treeStrings.SelectedItem is string str)) return; + + if(!(treeStrings.SelectedItem is string str)) + return; txtPublisher.Text = str; } @@ -38,7 +46,9 @@ namespace apprepodbmgr.Eto void OnBtnProductClick(object sender, EventArgs eventArgs) { txtProduct.Text = ""; - if(!(treeStrings.SelectedItem is string str)) return; + + if(!(treeStrings.SelectedItem is string str)) + return; txtProduct.Text = str; } @@ -46,7 +56,9 @@ namespace apprepodbmgr.Eto void OnBtnVersionClick(object sender, EventArgs eventArgs) { txtVersion.Text = ""; - if(!(treeStrings.SelectedItem is string str)) return; + + if(!(treeStrings.SelectedItem is string str)) + return; txtVersion.Text = str; } diff --git a/apprepodbmgr.Eto/pnlVersions.xeto.cs b/apprepodbmgr.Eto/pnlVersions.xeto.cs index 8f5354f..df39b48 100644 --- a/apprepodbmgr.Eto/pnlVersions.xeto.cs +++ b/apprepodbmgr.Eto/pnlVersions.xeto.cs @@ -19,22 +19,37 @@ namespace apprepodbmgr.Eto treeArchs.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r) + }, HeaderText = "Arch" }); + treeOs.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.name)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.name) + }, HeaderText = "Name" }); + treeOs.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r.version)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r.version) + }, HeaderText = "Version" }); + treeVersions.Columns.Add(new GridColumn { - DataCell = new TextBoxCell {Binding = Binding.Property(r => r)}, + DataCell = new TextBoxCell + { + Binding = Binding.Property(r => r) + }, HeaderText = "Version" }); }