diff --git a/DiscImageChef.Core/Statistics.cs b/DiscImageChef.Core/Statistics.cs index 94b0b9062..5c4080e7d 100644 --- a/DiscImageChef.Core/Statistics.cs +++ b/DiscImageChef.Core/Statistics.cs @@ -1304,5 +1304,33 @@ namespace DiscImageChef.Core ctx.SaveChanges(); } + + /// Adds a new remote to statistics + public static void AddRemote(string serverApplication, string serverVersion, string serverOperatingSystem, + string serverOperatingSystemVersion, string serverArchitecture) + { + if(Settings.Settings.Current.Stats == null || + !Settings.Settings.Current.Stats.MediaStats) + return; + + var ctx = DicContext.Create(Settings.Settings.LocalDbPath); + + ctx.RemoteApplications.Add(new RemoteApplication + { + Count = 1, Name = serverApplication, Synchronized = false, Version = serverVersion + }); + + ctx.RemoteArchitectures.Add(new RemoteArchitecture + { + Count = 1, Name = serverArchitecture, Synchronized = false + }); + + ctx.RemoteOperatingSystems.Add(new RemoteOperatingSystem + { + Count = 1, Name = serverOperatingSystem, Synchronized = false, Version = serverOperatingSystemVersion + }); + + ctx.SaveChanges(); + } } } \ No newline at end of file diff --git a/DiscImageChef.Devices/Device/List.cs b/DiscImageChef.Devices/Device/List.cs index 8d4c60a79..5e4b1be7b 100644 --- a/DiscImageChef.Devices/Device/List.cs +++ b/DiscImageChef.Devices/Device/List.cs @@ -56,7 +56,8 @@ namespace DiscImageChef.Devices [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string Bus; - [MarshalAs(UnmanagedType.U1)] public bool Supported; + [MarshalAs(UnmanagedType.U1)] + public bool Supported; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] public readonly byte[] Padding; @@ -64,29 +65,49 @@ namespace DiscImageChef.Devices public partial class Device { - public static DeviceInfo[] ListDevices(string dicRemote = null) + public static DeviceInfo[] ListDevices() => ListDevices(out _, out _, out _, out _, out _, out _); + + public static DeviceInfo[] ListDevices(out bool isRemote, out string serverApplication, + out string serverVersion, out string serverOperatingSystem, + out string serverOperatingSystemVersion, out string serverArchitecture, + string dicRemote = null) { - if (dicRemote is null) - switch (DetectOS.GetRealPlatformID()) + isRemote = false; + serverApplication = null; + serverVersion = null; + serverOperatingSystem = null; + serverOperatingSystemVersion = null; + serverArchitecture = null; + + if(dicRemote is null) + switch(DetectOS.GetRealPlatformID()) { case PlatformID.Win32NT: return Windows.ListDevices.GetList(); - case PlatformID.Linux: return Linux.ListDevices.GetList(); + case PlatformID.Linux: return Linux.ListDevices.GetList(); case PlatformID.FreeBSD: return FreeBSD.ListDevices.GetList(); default: - throw new InvalidOperationException( - $"Platform {DetectOS.GetRealPlatformID()} not yet supported."); + throw new + InvalidOperationException($"Platform {DetectOS.GetRealPlatformID()} not yet supported."); } try { - using (var remote = new Remote.Remote(dicRemote)) + using(var remote = new Remote.Remote(dicRemote)) { + isRemote = true; + serverApplication = remote.ServerApplication; + serverVersion = remote.ServerVersion; + serverOperatingSystem = remote.ServerOperatingSystem; + serverOperatingSystemVersion = remote.ServerOperatingSystemVersion; + serverArchitecture = remote.ServerArchitecture; + return remote.ListDevices(); } } - catch (Exception) + catch(Exception) { DicConsole.ErrorWriteLine("Error connecting to host."); + return new DeviceInfo[0]; } } diff --git a/DiscImageChef.Gui/Forms/frmDump.xeto.cs b/DiscImageChef.Gui/Forms/frmDump.xeto.cs index c14fae19c..5fc5401d4 100644 --- a/DiscImageChef.Gui/Forms/frmDump.xeto.cs +++ b/DiscImageChef.Gui/Forms/frmDump.xeto.cs @@ -82,47 +82,56 @@ namespace DiscImageChef.Gui.Forms stpRetries.Value = 5; stpSkipped.Value = 512; - if(scsiInfo != null) mediaType = scsiInfo.MediaType; + if(scsiInfo != null) + mediaType = scsiInfo.MediaType; else switch(deviceInfo.Type) { case DeviceType.SecureDigital: mediaType = MediaType.SecureDigital; + break; case DeviceType.MMC: mediaType = MediaType.MMC; + break; default: - if(deviceInfo.IsPcmcia) mediaType = MediaType.PCCardTypeII; - else if(deviceInfo.IsCompactFlash) mediaType = MediaType.CompactFlash; - else mediaType = MediaType.GENERIC_HDD; + if(deviceInfo.IsPcmcia) + mediaType = MediaType.PCCardTypeII; + else if(deviceInfo.IsCompactFlash) + mediaType = MediaType.CompactFlash; + else + mediaType = MediaType.GENERIC_HDD; + break; } ObservableCollection lstPlugins = new ObservableCollection(); PluginBase plugins = GetPluginBase.Instance; + foreach(IWritableImage plugin in plugins.WritableImages.Values.Where(p => p.SupportedMediaTypes.Contains(mediaType))) lstPlugins.Add(plugin); + cmbFormat.ItemTextBinding = Binding.Property((IWritableImage p) => p.Name); cmbFormat.ItemKeyBinding = Binding.Property((IWritableImage p) => p.Id.ToString()); cmbFormat.DataStore = lstPlugins; - List encodings = Encoding - .GetEncodings().Select(info => new CommonEncodingInfo - { - Name = info.Name, - DisplayName = - info.GetEncoding().EncodingName - }).ToList(); - encodings.AddRange(Claunia.Encoding.Encoding.GetEncodings() - .Select(info => new CommonEncodingInfo - { - Name = info.Name, DisplayName = info.DisplayName - })); + List encodings = Encoding.GetEncodings().Select(info => new CommonEncodingInfo + { + Name = info.Name, DisplayName = info.GetEncoding().EncodingName + }).ToList(); + + encodings.AddRange(Claunia.Encoding.Encoding.GetEncodings().Select(info => new CommonEncodingInfo + { + Name = info.Name, DisplayName = info.DisplayName + })); ObservableCollection lstEncodings = new ObservableCollection(); - foreach(CommonEncodingInfo info in encodings.OrderBy(t => t.DisplayName)) lstEncodings.Add(info); + + foreach(CommonEncodingInfo info in encodings.OrderBy(t => t.DisplayName)) + lstEncodings.Add(info); + cmbEncoding.ItemTextBinding = Binding.Property((CommonEncodingInfo p) => p.DisplayName); cmbEncoding.ItemKeyBinding = Binding.Property((CommonEncodingInfo p) => p.Name); cmbEncoding.DataStore = lstEncodings; @@ -172,9 +181,11 @@ namespace DiscImageChef.Gui.Forms case MediaType.VideoNowColor: case MediaType.VideoNowXp: chkTrack1Pregap.Visible = true; + break; default: chkTrack1Pregap.Visible = false; + break; } @@ -189,6 +200,7 @@ namespace DiscImageChef.Gui.Forms { grpOptions.Visible = false; btnDestination.Enabled = false; + return; } @@ -198,82 +210,91 @@ namespace DiscImageChef.Gui.Forms { grpOptions.Content = null; grpOptions.Visible = false; + return; } grpOptions.Visible = true; - StackLayout stkOptions = new StackLayout {Orientation = Orientation.Vertical}; + var stkOptions = new StackLayout + { + Orientation = Orientation.Vertical + }; foreach((string name, Type type, string description, object @default) option in plugin.SupportedOptions) switch(option.type.ToString()) { - case "System.Boolean": - CheckBox optBoolean = new CheckBox(); + case"System.Boolean": + var optBoolean = new CheckBox(); optBoolean.ID = "opt" + option.name; optBoolean.Text = option.description; optBoolean.Checked = (bool)option.@default; stkOptions.Items.Add(optBoolean); + break; - case "System.SByte": - case "System.Int16": - case "System.Int32": - case "System.Int64": - StackLayout stkNumber = new StackLayout(); + case"System.SByte": + case"System.Int16": + case"System.Int32": + case"System.Int64": + var stkNumber = new StackLayout(); stkNumber.Orientation = Orientation.Horizontal; - NumericStepper optNumber = new NumericStepper(); + var optNumber = new NumericStepper(); optNumber.ID = "opt" + option.name; optNumber.Value = Convert.ToDouble(option.@default); stkNumber.Items.Add(optNumber); - Label lblNumber = new Label(); + var lblNumber = new Label(); lblNumber.Text = option.description; stkNumber.Items.Add(lblNumber); stkOptions.Items.Add(stkNumber); + break; - case "System.Byte": - case "System.UInt16": - case "System.UInt32": - case "System.UInt64": - StackLayout stkUnsigned = new StackLayout(); + case"System.Byte": + case"System.UInt16": + case"System.UInt32": + case"System.UInt64": + var stkUnsigned = new StackLayout(); stkUnsigned.Orientation = Orientation.Horizontal; - NumericStepper optUnsigned = new NumericStepper(); + var optUnsigned = new NumericStepper(); optUnsigned.ID = "opt" + option.name; optUnsigned.MinValue = 0; optUnsigned.Value = Convert.ToDouble(option.@default); stkUnsigned.Items.Add(optUnsigned); - Label lblUnsigned = new Label(); + var lblUnsigned = new Label(); lblUnsigned.Text = option.description; stkUnsigned.Items.Add(lblUnsigned); stkOptions.Items.Add(stkUnsigned); + break; - case "System.Single": - case "System.Double": - StackLayout stkFloat = new StackLayout(); + case"System.Single": + case"System.Double": + var stkFloat = new StackLayout(); stkFloat.Orientation = Orientation.Horizontal; - NumericStepper optFloat = new NumericStepper(); + var optFloat = new NumericStepper(); optFloat.ID = "opt" + option.name; optFloat.DecimalPlaces = 2; optFloat.Value = Convert.ToDouble(option.@default); stkFloat.Items.Add(optFloat); - Label lblFloat = new Label(); + var lblFloat = new Label(); lblFloat.Text = option.description; stkFloat.Items.Add(lblFloat); stkOptions.Items.Add(stkFloat); + break; - case "System.Guid": + case"System.Guid": // TODO break; - case "System.String": - StackLayout stkString = new StackLayout(); + case"System.String": + var stkString = new StackLayout(); stkString.Orientation = Orientation.Horizontal; - Label lblString = new Label(); + var lblString = new Label(); lblString.Text = option.description; stkString.Items.Add(lblString); - TextBox optString = new TextBox(); + var optString = new TextBox(); optString.ID = "opt" + option.name; optString.Text = (string)option.@default; stkString.Items.Add(optString); stkOptions.Items.Add(stkString); + break; } @@ -282,9 +303,14 @@ namespace DiscImageChef.Gui.Forms void OnBtnDestinationClick(object sender, EventArgs e) { - if(!(cmbFormat.SelectedValue is IWritableImage plugin)) return; + if(!(cmbFormat.SelectedValue is IWritableImage plugin)) + return; + + var dlgDestination = new SaveFileDialog + { + Title = "Choose destination file" + }; - SaveFileDialog dlgDestination = new SaveFileDialog {Title = "Choose destination file"}; dlgDestination.Filters.Add(new FileFilter(plugin.Name, plugin.KnownExtensions.ToArray())); DialogResult result = dlgDestination.ShowDialog(this); @@ -293,6 +319,7 @@ namespace DiscImageChef.Gui.Forms { txtDestination.Text = ""; outputPrefix = null; + return; } @@ -300,8 +327,10 @@ namespace DiscImageChef.Gui.Forms dlgDestination.FileName += plugin.KnownExtensions.First(); txtDestination.Text = dlgDestination.FileName; + outputPrefix = Path.Combine(Path.GetDirectoryName(dlgDestination.FileName), Path.GetFileNameWithoutExtension(dlgDestination.FileName)); + chkResume.Checked = true; } @@ -316,11 +345,15 @@ namespace DiscImageChef.Gui.Forms if(chkExistingMetadata.Checked == false) { sidecar = null; + return; } - OpenFileDialog dlgMetadata = - new OpenFileDialog {Title = "Choose existing metadata sidecar", CheckFileExists = true}; + var dlgMetadata = new OpenFileDialog + { + Title = "Choose existing metadata sidecar", CheckFileExists = true + }; + dlgMetadata.Filters.Add(new FileFilter("CICM XML metadata", ".xml")); DialogResult result = dlgMetadata.ShowDialog(this); @@ -328,13 +361,15 @@ namespace DiscImageChef.Gui.Forms if(result != DialogResult.Ok) { chkExistingMetadata.Checked = false; + return; } - XmlSerializer sidecarXs = new XmlSerializer(typeof(CICMMetadataType)); + var sidecarXs = new XmlSerializer(typeof(CICMMetadataType)); + try { - StreamReader sr = new StreamReader(dlgMetadata.FileName); + var sr = new StreamReader(dlgMetadata.FileName); sidecar = (CICMMetadataType)sidecarXs.Deserialize(sr); sr.Close(); } @@ -347,18 +382,21 @@ namespace DiscImageChef.Gui.Forms void OnChkResumeCheckedChanged(object sender, EventArgs e) { - if(chkResume.Checked == false) return; + if(chkResume.Checked == false) + return; - if(outputPrefix != null) CheckResumeFile(); + if(outputPrefix != null) + CheckResumeFile(); } void CheckResumeFile() { resume = null; - XmlSerializer xs = new XmlSerializer(typeof(Resume)); + var xs = new XmlSerializer(typeof(Resume)); + try { - StreamReader sr = new StreamReader(outputPrefix + ".resume.xml"); + var sr = new StreamReader(outputPrefix + ".resume.xml"); resume = (Resume)xs.Deserialize(sr); sr.Close(); } @@ -366,21 +404,22 @@ namespace DiscImageChef.Gui.Forms { MessageBox.Show("Incorrect resume file, cannot use it...", MessageBoxType.Error); chkResume.Checked = false; + return; } - if(resume == null || resume.NextBlock <= resume.LastBlock || - resume.BadBlocks.Count != 0 && !resume.Tape) return; + if(resume == null || + resume.NextBlock <= resume.LastBlock || + (resume.BadBlocks.Count != 0 && !resume.Tape)) + return; MessageBox.Show("Media already dumped correctly, please choose another destination...", MessageBoxType.Warning); + chkResume.Checked = false; } - void OnBtnCloseClick(object sender, EventArgs e) - { - Close(); - } + void OnBtnCloseClick(object sender, EventArgs e) => Close(); void OnBtnStopClick(object sender, EventArgs e) { @@ -400,19 +439,26 @@ namespace DiscImageChef.Gui.Forms stkOptions.Visible = false; UpdateStatus("Opening device..."); + try { dev = new Device(devicePath); + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); + if(dev.Error) { StoppingErrorMessage($"Error {dev.LastError} opening device."); + return; } } catch(Exception exception) { StoppingErrorMessage($"Exception {exception.Message} opening device."); + return; } @@ -422,16 +468,21 @@ namespace DiscImageChef.Gui.Forms if(!(cmbFormat.SelectedValue is IWritableImage outputFormat)) { StoppingErrorMessage("Cannot open output plugin."); + return; } Encoding encoding = null; if(cmbEncoding.SelectedValue is CommonEncodingInfo encodingInfo) - try { encoding = Claunia.Encoding.Encoding.GetEncoding(encodingInfo.Name); } + try + { + encoding = Claunia.Encoding.Encoding.GetEncoding(encodingInfo.Name); + } catch(ArgumentException) { StoppingErrorMessage("Specified encoding is not supported."); + return; } @@ -446,12 +497,15 @@ namespace DiscImageChef.Gui.Forms { case CheckBox optBoolean: value = optBoolean.Checked?.ToString(); + break; case NumericStepper optNumber: value = optNumber.Value.ToString(CultureInfo.CurrentCulture); + break; case TextBox optString: value = optString.Text; + break; default: continue; } @@ -461,7 +515,7 @@ namespace DiscImageChef.Gui.Forms parsedOptions.Add(key, value); } - DumpLog dumpLog = new DumpLog(outputPrefix + ".log", dev); + var dumpLog = new DumpLog(outputPrefix + ".log", dev); dumpLog.WriteLine("Output image format: {0}.", outputFormat.Name); @@ -495,105 +549,92 @@ namespace DiscImageChef.Gui.Forms WorkFinished(); } - void WorkFinished() + void WorkFinished() => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => + btnClose.Visible = true; + btnStop.Visible = false; + stkProgress1.Visible = false; + stkProgress2.Visible = false; + }); + + void EndProgress2() => Application.Instance.Invoke(() => + { + stkProgress2.Visible = false; + }); + + void UpdateProgress2(string text, long current, long maximum) => Application.Instance.Invoke(() => + { + lblProgress2.Text = text; + prgProgress2.Indeterminate = false; + prgProgress2.MinValue = 0; + + if(maximum > int.MaxValue) { - btnClose.Visible = true; - btnStop.Visible = false; - stkProgress1.Visible = false; - stkProgress2.Visible = false; - }); - } - - void EndProgress2() - { - Application.Instance.Invoke(() => { stkProgress2.Visible = false; }); - } - - void UpdateProgress2(string text, long current, long maximum) - { - Application.Instance.Invoke(() => + prgProgress2.MaxValue = (int)(maximum / int.MaxValue); + prgProgress2.Value = (int)(current / int.MaxValue); + } + else { - lblProgress2.Text = text; - prgProgress2.Indeterminate = false; - prgProgress2.MinValue = 0; - if(maximum > int.MaxValue) - { - prgProgress2.MaxValue = (int)(maximum / int.MaxValue); - prgProgress2.Value = (int)(current / int.MaxValue); - } - else - { - prgProgress2.MaxValue = (int)maximum; - prgProgress2.Value = (int)current; - } - }); - } + prgProgress2.MaxValue = (int)maximum; + prgProgress2.Value = (int)current; + } + }); - void InitProgress2() + void InitProgress2() => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => { stkProgress2.Visible = true; }); - } + stkProgress2.Visible = true; + }); - void EndProgress() + void EndProgress() => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => { stkProgress1.Visible = false; }); - } + stkProgress1.Visible = false; + }); - void UpdateProgress(string text, long current, long maximum) + void UpdateProgress(string text, long current, long maximum) => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => + lblProgress.Text = text; + prgProgress.Indeterminate = false; + prgProgress.MinValue = 0; + + if(maximum > int.MaxValue) { - lblProgress.Text = text; - prgProgress.Indeterminate = false; - prgProgress.MinValue = 0; - if(maximum > int.MaxValue) - { - prgProgress.MaxValue = (int)(maximum / int.MaxValue); - prgProgress.Value = (int)(current / int.MaxValue); - } - else - { - prgProgress.MaxValue = (int)maximum; - prgProgress.Value = (int)current; - } - }); - } - - void InitProgress() - { - Application.Instance.Invoke(() => { stkProgress1.Visible = true; }); - } - - void PulseProgress(string text) - { - Application.Instance.Invoke(() => + prgProgress.MaxValue = (int)(maximum / int.MaxValue); + prgProgress.Value = (int)(current / int.MaxValue); + } + else { - lblProgress.Text = text; - prgProgress.Indeterminate = true; - }); - } + prgProgress.MaxValue = (int)maximum; + prgProgress.Value = (int)current; + } + }); - void StoppingErrorMessage(string text) + void InitProgress() => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => - { - ErrorMessage(text); - MessageBox.Show(text, MessageBoxType.Error); - WorkFinished(); - }); - } + stkProgress1.Visible = true; + }); - void ErrorMessage(string text) + void PulseProgress(string text) => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => { txtLog.Append(text + Environment.NewLine, true); }); - } + lblProgress.Text = text; + prgProgress.Indeterminate = true; + }); - void UpdateStatus(string text) + void StoppingErrorMessage(string text) => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => { txtLog.Append(text + Environment.NewLine, true); }); - } + ErrorMessage(text); + MessageBox.Show(text, MessageBoxType.Error); + WorkFinished(); + }); + + void ErrorMessage(string text) => Application.Instance.Invoke(() => + { + txtLog.Append(text + Environment.NewLine, true); + }); + + void UpdateStatus(string text) => Application.Instance.Invoke(() => + { + txtLog.Append(text + Environment.NewLine, true); + }); class CommonEncodingInfo { diff --git a/DiscImageChef.Gui/Forms/frmMain.xeto.cs b/DiscImageChef.Gui/Forms/frmMain.xeto.cs index 5e0de956a..f5aeabec6 100644 --- a/DiscImageChef.Gui/Forms/frmMain.xeto.cs +++ b/DiscImageChef.Gui/Forms/frmMain.xeto.cs @@ -58,26 +58,24 @@ namespace DiscImageChef.Gui.Forms { public class frmMain : Form { - bool closing; - Bitmap devicesIcon; - Bitmap ejectIcon; - GridView grdFiles; - Bitmap hardDiskIcon; - Bitmap imagesIcon; - Label lblError; - /// - /// This is to remember that column is an image to be set in future - /// - Image nullImage; - Bitmap opticalIcon; - TreeGridItem placeholderItem; - Bitmap removableIcon; - Bitmap sdIcon; - Bitmap tapeIcon; - TreeGridView treeImages; - TreeGridItemCollection treeImagesItems; - ContextMenu treeImagesMenu; - Bitmap usbIcon; + bool closing; + readonly Bitmap devicesIcon; + readonly Bitmap ejectIcon; + GridView grdFiles; + readonly Bitmap hardDiskIcon; + readonly Bitmap imagesIcon; + readonly Label lblError; + /// This is to remember that column is an image to be set in future + readonly Image nullImage; + readonly Bitmap opticalIcon; + readonly TreeGridItem placeholderItem; + readonly Bitmap removableIcon; + readonly Bitmap sdIcon; + readonly Bitmap tapeIcon; + TreeGridView treeImages; + readonly TreeGridItemCollection treeImagesItems; + readonly ContextMenu treeImagesMenu; + readonly Bitmap usbIcon; public frmMain(bool debug, bool verbose) { @@ -93,7 +91,10 @@ namespace DiscImageChef.Gui.Forms treeImagesItems = new TreeGridItemCollection(); - treeImages.Columns.Add(new GridColumn {HeaderText = "Name", DataCell = new ImageTextCell(0, 1)}); + treeImages.Columns.Add(new GridColumn + { + HeaderText = "Name", DataCell = new ImageTextCell(0, 1) + }); treeImages.AllowMultipleSelection = false; treeImages.ShowHeader = false; @@ -101,40 +102,67 @@ namespace DiscImageChef.Gui.Forms // TODO: SVG imagesIcon = - new Bitmap(ResourceHandler - .GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.inode-directory.png")); - devicesIcon = - new Bitmap(ResourceHandler - .GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.computer.png")); - hardDiskIcon = - new Bitmap(ResourceHandler - .GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-harddisk.png")); - opticalIcon = - new Bitmap(ResourceHandler - .GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-optical.png")); - usbIcon = - new Bitmap(ResourceHandler - .GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-removable-media-usb.png")); - removableIcon = - new Bitmap(ResourceHandler - .GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-removable-media.png")); - sdIcon = - new Bitmap(ResourceHandler - .GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.media-flash-sd-mmc.png")); - tapeIcon = - new Bitmap(ResourceHandler - .GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.media-tape.png")); - ejectIcon = - new Bitmap(ResourceHandler - .GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.media-eject.png")); + new Bitmap(ResourceHandler. + GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.inode-directory.png")); - imagesRoot = new TreeGridItem {Values = new object[] {imagesIcon, "Images"}}; - devicesRoot = new TreeGridItem {Values = new object[] {devicesIcon, "Devices"}}; + devicesIcon = + new Bitmap(ResourceHandler. + GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.computer.png")); + + hardDiskIcon = + new Bitmap(ResourceHandler. + GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-harddisk.png")); + + opticalIcon = + new Bitmap(ResourceHandler. + GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-optical.png")); + + usbIcon = + new Bitmap(ResourceHandler. + GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-removable-media-usb.png")); + + removableIcon = + new Bitmap(ResourceHandler. + GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-removable-media.png")); + + sdIcon = + new Bitmap(ResourceHandler. + GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.media-flash-sd-mmc.png")); + + tapeIcon = + new Bitmap(ResourceHandler. + GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.media-tape.png")); + + ejectIcon = + new Bitmap(ResourceHandler. + GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.media-eject.png")); + + imagesRoot = new TreeGridItem + { + Values = new object[] + { + imagesIcon, "Images" + } + }; + + devicesRoot = new TreeGridItem + { + Values = new object[] + { + devicesIcon, "Devices" + } + }; treeImagesItems.Add(imagesRoot); treeImagesItems.Add(devicesRoot); - placeholderItem = new TreeGridItem {Values = new object[] {nullImage, "You should not be seeing this"}}; + placeholderItem = new TreeGridItem + { + Values = new object[] + { + nullImage, "You should not be seeing this" + } + }; Closing += OnClosing; @@ -148,73 +176,143 @@ namespace DiscImageChef.Gui.Forms OnTreeImagesSelectedItemChanged(treeImages, e); treeImagesMenu.Items.Clear(); - ButtonMenuItem menuItem = new ButtonMenuItem {Text = "Close all images"}; + + var menuItem = new ButtonMenuItem + { + Text = "Close all images" + }; + menuItem.Click += CloseAllImages; treeImagesMenu.Items.Add(menuItem); - menuItem = new ButtonMenuItem {Text = "Refresh devices"}; + + menuItem = new ButtonMenuItem + { + Text = "Refresh devices" + }; + menuItem.Click += OnDeviceRefresh; treeImagesMenu.Items.Add(menuItem); - if(!(treeImages.SelectedItem is TreeGridItem selectedItem)) return; + if(!(treeImages.SelectedItem is TreeGridItem selectedItem)) + return; - if(selectedItem.Values.Length < 4) return; + if(selectedItem.Values.Length < 4) + return; if(selectedItem.Values[3] is pnlImageInfo imageInfo) { - IMediaImage image = selectedItem.Values[5] as IMediaImage; + var image = selectedItem.Values[5] as IMediaImage; // TODO: Global pool of forms treeImagesMenu.Items.Add(new SeparatorMenuItem()); - menuItem = new ButtonMenuItem {Text = "Calculate entropy"}; - menuItem.Click += (a, b) => { new frmImageEntropy(image).Show(); }; + menuItem = new ButtonMenuItem + { + Text = "Calculate entropy" + }; + + menuItem.Click += (a, b) => + { + new frmImageEntropy(image).Show(); + }; + treeImagesMenu.Items.Add(menuItem); - menuItem = new ButtonMenuItem {Text = "Verify"}; - menuItem.Click += (a, b) => { new frmImageVerify(image).Show(); }; + + menuItem = new ButtonMenuItem + { + Text = "Verify" + }; + + menuItem.Click += (a, b) => + { + new frmImageVerify(image).Show(); + }; + treeImagesMenu.Items.Add(menuItem); - menuItem = new ButtonMenuItem {Text = "Checksum"}; - menuItem.Click += (a, b) => { new frmImageChecksum(image).Show(); }; + + menuItem = new ButtonMenuItem + { + Text = "Checksum" + }; + + menuItem.Click += (a, b) => + { + new frmImageChecksum(image).Show(); + }; + treeImagesMenu.Items.Add(menuItem); - menuItem = new ButtonMenuItem {Text = "Convert to..."}; - menuItem.Click += (a, b) => { new frmImageConvert(image, selectedItem.Values[2] as string).Show(); }; + + menuItem = new ButtonMenuItem + { + Text = "Convert to..." + }; + + menuItem.Click += (a, b) => + { + new frmImageConvert(image, selectedItem.Values[2] as string).Show(); + }; + treeImagesMenu.Items.Add(menuItem); - menuItem = new ButtonMenuItem {Text = "Create CICM XML sidecar..."}; + + menuItem = new ButtonMenuItem + { + Text = "Create CICM XML sidecar..." + }; + menuItem.Click += (a, b) => { // TODO: Pass thru chosen default encoding new frmImageSidecar(image, selectedItem.Values[2] as string, ((IFilter)selectedItem.Values[4]).Id, null).Show(); }; - treeImagesMenu.Items.Add(menuItem); - menuItem = new ButtonMenuItem {Text = "View sectors"}; - menuItem.Click += (a, b) => { new frmPrintHex(image).Show(); }; + treeImagesMenu.Items.Add(menuItem); - if(!image.Info.ReadableMediaTags.Any()) return; + menuItem = new ButtonMenuItem + { + Text = "View sectors" + }; + + menuItem.Click += (a, b) => + { + new frmPrintHex(image).Show(); + }; + + treeImagesMenu.Items.Add(menuItem); + + if(!image.Info.ReadableMediaTags.Any()) + return; + + menuItem = new ButtonMenuItem + { + Text = "Decode media tags" + }; + + menuItem.Click += (a, b) => + { + new frmDecodeMediaTags(image).Show(); + }; - menuItem = new ButtonMenuItem {Text = "Decode media tags"}; - menuItem.Click += (a, b) => { new frmDecodeMediaTags(image).Show(); }; treeImagesMenu.Items.Add(menuItem); } } - void CloseAllImages(object sender, EventArgs eventArgs) - { - // TODO - MessageBox.Show("Not yet implemented"); - } + // TODO + void CloseAllImages(object sender, EventArgs eventArgs) => MessageBox.Show("Not yet implemented"); protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if(Settings.Settings.Current.GdprCompliance < DicSettings.GdprLevel) new dlgSettings(true).ShowModal(this); + if(Settings.Settings.Current.GdprCompliance < DicSettings.GdprLevel) + new dlgSettings(true).ShowModal(this); } void OnClosing(object sender, CancelEventArgs e) { // This prevents an infinite loop of crashes :p - if(closing) return; + if(closing) + return; closing = true; Application.Instance.Quit(); @@ -223,17 +321,23 @@ namespace DiscImageChef.Gui.Forms protected void OnMenuOpen(object sender, EventArgs e) { // TODO: Extensions - OpenFileDialog dlgOpenImage = new OpenFileDialog {Title = "Choose image to open"}; + var dlgOpenImage = new OpenFileDialog + { + Title = "Choose image to open" + }; DialogResult result = dlgOpenImage.ShowDialog(this); - if(result != DialogResult.Ok) return; - FiltersList filtersList = new FiltersList(); - IFilter inputFilter = filtersList.GetFilter(dlgOpenImage.FileName); + if(result != DialogResult.Ok) + return; + + var filtersList = new FiltersList(); + IFilter inputFilter = filtersList.GetFilter(dlgOpenImage.FileName); if(inputFilter == null) { MessageBox.Show("Cannot open specified file.", MessageBoxType.Error); + return; } @@ -244,6 +348,7 @@ namespace DiscImageChef.Gui.Forms if(imageFormat == null) { MessageBox.Show("Image format not identified.", MessageBoxType.Error); + return; } @@ -256,23 +361,23 @@ namespace DiscImageChef.Gui.Forms MessageBox.Show("Unable to open image format", MessageBoxType.Error); DicConsole.ErrorWriteLine("Unable to open image format"); DicConsole.ErrorWriteLine("No error given"); + return; } // TODO: SVG Stream logo = - ResourceHandler - .GetResourceStream($"DiscImageChef.Gui.Assets.Logos.Media.{imageFormat.Info.MediaType}.png"); + ResourceHandler. + GetResourceStream($"DiscImageChef.Gui.Assets.Logos.Media.{imageFormat.Info.MediaType}.png"); - TreeGridItem imageGridItem = new TreeGridItem + var imageGridItem = new TreeGridItem { Values = new object[] { logo == null ? null : new Bitmap(logo), $"{Path.GetFileName(dlgOpenImage.FileName)} ({imageFormat.Info.MediaType})", - dlgOpenImage.FileName, - new pnlImageInfo(dlgOpenImage.FileName, inputFilter, imageFormat), inputFilter, - imageFormat + dlgOpenImage.FileName, new pnlImageInfo(dlgOpenImage.FileName, inputFilter, imageFormat), + inputFilter, imageFormat } }; @@ -296,7 +401,7 @@ namespace DiscImageChef.Gui.Forms foreach(string scheme in partitions.Select(p => p.Scheme).Distinct().OrderBy(s => s)) { - TreeGridItem schemeGridItem = new TreeGridItem + var schemeGridItem = new TreeGridItem { Values = new object[] { @@ -305,10 +410,10 @@ namespace DiscImageChef.Gui.Forms } }; - foreach(Partition partition in partitions - .Where(p => p.Scheme == scheme).OrderBy(p => p.Start)) + foreach(Partition partition in partitions. + Where(p => p.Scheme == scheme).OrderBy(p => p.Start)) { - TreeGridItem partitionGridItem = new TreeGridItem + var partitionGridItem = new TreeGridItem { Values = new object[] { @@ -320,7 +425,9 @@ namespace DiscImageChef.Gui.Forms DicConsole.WriteLine("Identifying filesystem on partition"); Core.Filesystems.Identify(imageFormat, out idPlugins, partition); - if(idPlugins.Count == 0) DicConsole.WriteLine("Filesystem not identified"); + + if(idPlugins.Count == 0) + DicConsole.WriteLine("Filesystem not identified"); else { DicConsole.WriteLine($"Identified by {idPlugins.Count} plugins"); @@ -330,7 +437,7 @@ namespace DiscImageChef.Gui.Forms { plugin.GetInformation(imageFormat, partition, out string information, null); - IReadOnlyFilesystem fsPlugin = plugin as IReadOnlyFilesystem; + var fsPlugin = plugin as IReadOnlyFilesystem; if(fsPlugin != null) { @@ -338,16 +445,16 @@ namespace DiscImageChef.Gui.Forms fsPlugin.Mount(imageFormat, partition, null, new Dictionary(), null); - if(error != Errno.NoError) fsPlugin = null; + if(error != Errno.NoError) + fsPlugin = null; } - TreeGridItem filesystemGridItem = new TreeGridItem + var filesystemGridItem = new TreeGridItem { Values = new object[] { nullImage, // TODO: Add icons to filesystems - plugin.XmlFsType.VolumeName is null - ? $"{plugin.XmlFsType.Type}" + plugin.XmlFsType.VolumeName is null ? $"{plugin.XmlFsType.Type}" : $"{plugin.XmlFsType.VolumeName} ({plugin.XmlFsType.Type})", fsPlugin, new pnlFilesystem(plugin.XmlFsType, information) } @@ -373,15 +480,16 @@ namespace DiscImageChef.Gui.Forms if(checkraw) { - Partition wholePart = new Partition + var wholePart = new Partition { - Name = "Whole device", - Length = imageFormat.Info.Sectors, - Size = imageFormat.Info.Sectors * imageFormat.Info.SectorSize + Name = "Whole device", Length = imageFormat.Info.Sectors, + Size = imageFormat.Info.Sectors * imageFormat.Info.SectorSize }; Core.Filesystems.Identify(imageFormat, out idPlugins, wholePart); - if(idPlugins.Count == 0) DicConsole.WriteLine("Filesystem not identified"); + + if(idPlugins.Count == 0) + DicConsole.WriteLine("Filesystem not identified"); else { DicConsole.WriteLine($"Identified by {idPlugins.Count} plugins"); @@ -391,23 +499,23 @@ namespace DiscImageChef.Gui.Forms { plugin.GetInformation(imageFormat, wholePart, out string information, null); - IReadOnlyFilesystem fsPlugin = plugin as IReadOnlyFilesystem; + var fsPlugin = plugin as IReadOnlyFilesystem; if(fsPlugin != null) { Errno error = fsPlugin.Mount(imageFormat, wholePart, null, new Dictionary(), null); - if(error != Errno.NoError) fsPlugin = null; + if(error != Errno.NoError) + fsPlugin = null; } - TreeGridItem filesystemGridItem = new TreeGridItem + var filesystemGridItem = new TreeGridItem { Values = new object[] { nullImage, // TODO: Add icons to filesystems - plugin.XmlFsType.VolumeName is null - ? $"{plugin.XmlFsType.Type}" + plugin.XmlFsType.VolumeName is null ? $"{plugin.XmlFsType.Type}" : $"{plugin.XmlFsType.VolumeName} ({plugin.XmlFsType.Type})", fsPlugin, new pnlFilesystem(plugin.XmlFsType, information) } @@ -452,9 +560,12 @@ namespace DiscImageChef.Gui.Forms protected void OnMenuAbout(object sender, EventArgs e) { - AboutDialog dlgAbout = new AboutDialog + var dlgAbout = new AboutDialog { - Developers = new[] {"Natalia Portillo", "Michael Drüing"}, + Developers = new[] + { + "Natalia Portillo", "Michael Drüing" + }, License = "This program is free software: you can redistribute it and/or modify\n" + "it under the terms of the GNU General public License as\n" + "published by the Free Software Foundation, either version 3 of the\n" + @@ -465,27 +576,18 @@ namespace DiscImageChef.Gui.Forms "GNU General public License for more details.\n\n" + "You should have received a copy of the GNU General public License\n" + "along with this program. If not, see .", - ProgramName = "The Disc Image Chef", - Website = new Uri("https://github.com/claunia"), + ProgramName = "The Disc Image Chef", Website = new Uri("https://github.com/claunia"), WebsiteLabel = "Source code on..." }; + dlgAbout.ShowDialog(this); } - protected void OnMenuQuit(object sender, EventArgs e) - { - Application.Instance.Quit(); - } + protected void OnMenuQuit(object sender, EventArgs e) => Application.Instance.Quit(); - protected void OnDeviceRefresh(object sender, EventArgs e) - { - RefreshDevices(); - } + protected void OnDeviceRefresh(object sender, EventArgs e) => RefreshDevices(); - protected void OnMenuSettings(object sender, EventArgs e) - { - new dlgSettings(false).ShowModal(this); - } + protected void OnMenuSettings(object sender, EventArgs e) => new dlgSettings(false).ShowModal(this); protected override void OnLoadComplete(EventArgs e) { @@ -501,14 +603,14 @@ namespace DiscImageChef.Gui.Forms DicConsole.WriteLine("Refreshing devices"); devicesRoot.Children.Clear(); - foreach(DeviceInfo device in Device.ListDevices().Where(d => d.Supported).OrderBy(d => d.Vendor) - .ThenBy(d => d.Model)) + foreach(DeviceInfo device in Device.ListDevices().Where(d => d.Supported).OrderBy(d => d.Vendor). + ThenBy(d => d.Model)) { DicConsole.DebugWriteLine("Main window", "Found supported device model {0} by manufacturer {1} on bus {2} and path {3}", device.Model, device.Vendor, device.Bus, device.Path); - TreeGridItem devItem = new TreeGridItem + var devItem = new TreeGridItem { Values = new object[] { @@ -518,7 +620,11 @@ namespace DiscImageChef.Gui.Forms try { - Device dev = new Device(device.Path); + var dev = new Device(device.Path); + + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); switch(dev.Type) { @@ -529,22 +635,24 @@ namespace DiscImageChef.Gui.Forms case PeripheralDeviceTypes.DirectAccess: case PeripheralDeviceTypes.SCSIZonedBlockDevice: case PeripheralDeviceTypes.SimplifiedDevice: - devItem.Values[0] = dev.IsRemovable - ? dev.IsUsb - ? usbIcon - : removableIcon - : hardDiskIcon; + devItem.Values[0] = dev.IsRemovable ? dev.IsUsb + ? usbIcon + : removableIcon : hardDiskIcon; + break; case PeripheralDeviceTypes.SequentialAccess: devItem.Values[0] = tapeIcon; + break; case PeripheralDeviceTypes.OpticalDevice: case PeripheralDeviceTypes.WriteOnceDevice: case PeripheralDeviceTypes.OCRWDevice: devItem.Values[0] = removableIcon; + break; case PeripheralDeviceTypes.MultiMediaDevice: devItem.Values[0] = opticalIcon; + break; } @@ -552,9 +660,11 @@ namespace DiscImageChef.Gui.Forms case DeviceType.SecureDigital: case DeviceType.MMC: devItem.Values[0] = sdIcon; + break; case DeviceType.NVMe: devItem.Values[0] = nullImage; + break; } @@ -571,37 +681,34 @@ namespace DiscImageChef.Gui.Forms treeImages.ReloadData(); } - catch(InvalidOperationException ex) { DicConsole.ErrorWriteLine(ex.Message); } + catch(InvalidOperationException ex) + { + DicConsole.ErrorWriteLine(ex.Message); + } } - protected void OnMenuConsole(object sender, EventArgs e) - { - new frmConsole().Show(); - } + protected void OnMenuConsole(object sender, EventArgs e) => new frmConsole().Show(); - protected void OnMenuPlugins(object sender, EventArgs e) - { - new dlgPlugins().ShowModal(this); - } + protected void OnMenuPlugins(object sender, EventArgs e) => new dlgPlugins().ShowModal(this); - protected void OnMenuEncodings(object sender, EventArgs e) - { - new dlgEncodings().ShowModal(this); - } + protected void OnMenuEncodings(object sender, EventArgs e) => new dlgEncodings().ShowModal(this); - protected void OnMenuBenchmark(object sender, EventArgs e) - { - new dlgBenchmark().ShowModal(this); - } + protected void OnMenuBenchmark(object sender, EventArgs e) => new dlgBenchmark().ShowModal(this); protected void OnMenuStatistics(object sender, EventArgs e) { - DicContext ctx = DicContext.Create(Settings.Settings.LocalDbPath); + var ctx = DicContext.Create(Settings.Settings.LocalDbPath); - if(!ctx.Commands.Any() && !ctx.Filesystems.Any() && !ctx.Filters.Any() && !ctx.MediaFormats.Any() && - !ctx.Medias.Any() && !ctx.Partitions.Any() && !ctx.SeenDevices.Any()) + if(!ctx.Commands.Any() && + !ctx.Filesystems.Any() && + !ctx.Filters.Any() && + !ctx.MediaFormats.Any() && + !ctx.Medias.Any() && + !ctx.Partitions.Any() && + !ctx.SeenDevices.Any()) { MessageBox.Show("There are no statistics."); + return; } @@ -610,33 +717,44 @@ namespace DiscImageChef.Gui.Forms protected void OnTreeImagesSelectedItemChanged(object sender, EventArgs e) { - if(!(sender is TreeGridView tree)) return; + if(!(sender is TreeGridView tree)) + return; - if(!(tree.SelectedItem is TreeGridItem selectedItem)) return; + if(!(tree.SelectedItem is TreeGridItem selectedItem)) + return; splMain.Panel2 = null; - if(selectedItem.Values.Length >= 4 && selectedItem.Values[3] is Panel infoPanel) + if(selectedItem.Values.Length >= 4 && + selectedItem.Values[3] is Panel infoPanel) { splMain.Panel2 = infoPanel; + return; } - if(selectedItem.Values.Length < 4) return; + if(selectedItem.Values.Length < 4) + return; switch(selectedItem.Values[3]) { case null when selectedItem.Parent == devicesRoot: try { - Device dev = new Device((string)selectedItem.Values[2]); + var dev = new Device((string)selectedItem.Values[2]); + + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); + if(dev.Error) { selectedItem.Values[3] = $"Error {dev.LastError} opening device"; + return; } - Core.Devices.Info.DeviceInfo devInfo = new Core.Devices.Info.DeviceInfo(dev); + var devInfo = new Core.Devices.Info.DeviceInfo(dev); selectedItem.Values[3] = new pnlDeviceInfo(devInfo); splMain.Panel2 = (Panel)selectedItem.Values[3]; @@ -655,12 +773,13 @@ namespace DiscImageChef.Gui.Forms case string devErrorMessage when selectedItem.Parent == devicesRoot: lblError.Text = devErrorMessage; splMain.Panel2 = lblError; + break; case Dictionary files: splMain.Panel2 = new pnlListFiles(selectedItem.Values[2] as IReadOnlyFilesystem, files, - selectedItem.Values[1] as string == "/" - ? "/" + selectedItem.Values[1] as string == "/" ? "/" : selectedItem.Values[4] as string); + break; case null when selectedItem.Values.Length >= 5 && selectedItem.Values[4] is string dirPath && selectedItem.Values[2] is IReadOnlyFilesystem fsPlugin: @@ -670,6 +789,7 @@ namespace DiscImageChef.Gui.Forms { MessageBox.Show($"Error {errno} trying to read \"{dirPath}\" of chosen filesystem", MessageBoxType.Error); + break; } @@ -681,16 +801,19 @@ namespace DiscImageChef.Gui.Forms if(errno != Errno.NoError) { - DicConsole - .ErrorWriteLine($"Error {errno} trying to get information about filesystem entry named {dirent}"); + DicConsole. + ErrorWriteLine($"Error {errno} trying to get information about filesystem entry named {dirent}"); + continue; } - if(!stat.Attributes.HasFlag(FileAttributes.Directory)) filesNew.Add(dirent, stat); + if(!stat.Attributes.HasFlag(FileAttributes.Directory)) + filesNew.Add(dirent, stat); } selectedItem.Values[3] = filesNew; splMain.Panel2 = new pnlListFiles(fsPlugin, filesNew, dirPath); + break; } } @@ -699,23 +822,31 @@ namespace DiscImageChef.Gui.Forms { // First expansion of a device if((e.Item as TreeGridItem)?.Children?.Count != 1 || - ((TreeGridItem)e.Item).Children[0] != placeholderItem) return; + ((TreeGridItem)e.Item).Children[0] != placeholderItem) + return; if(((TreeGridItem)e.Item).Parent == devicesRoot) { - TreeGridItem deviceItem = (TreeGridItem)e.Item; + var deviceItem = (TreeGridItem)e.Item; deviceItem.Children.Clear(); Device dev; + try { dev = new Device((string)deviceItem.Values[2]); + + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); + if(dev.Error) { deviceItem.Values[3] = $"Error {dev.LastError} opening device"; e.Cancel = true; treeImages.ReloadData(); treeImages.SelectedItem = deviceItem; + return; } } @@ -726,6 +857,7 @@ namespace DiscImageChef.Gui.Forms treeImages.ReloadData(); DicConsole.ErrorWriteLine(ex.Message); treeImages.SelectedItem = deviceItem; + return; } @@ -734,33 +866,34 @@ namespace DiscImageChef.Gui.Forms { Values = new object[] { - nullImage, - "Non-removable device commands not yet implemented" + nullImage, "Non-removable device commands not yet implemented" } }); else { // TODO: Removable non-SCSI? - ScsiInfo scsiInfo = new ScsiInfo(dev); + var scsiInfo = new ScsiInfo(dev); if(!scsiInfo.MediaInserted) deviceItem.Children.Add(new TreeGridItem { - Values = new object[] {ejectIcon, "No media inserted"} + Values = new object[] + { + ejectIcon, "No media inserted" + } }); else { // TODO: SVG Stream logo = - ResourceHandler - .GetResourceStream($"DiscImageChef.Gui.Assets.Logos.Media.{scsiInfo.MediaType}.png"); + ResourceHandler. + GetResourceStream($"DiscImageChef.Gui.Assets.Logos.Media.{scsiInfo.MediaType}.png"); deviceItem.Children.Add(new TreeGridItem { Values = new[] { - logo == null ? null : new Bitmap(logo), - scsiInfo.MediaType, deviceItem.Values[2], + logo == null ? null : new Bitmap(logo), scsiInfo.MediaType, deviceItem.Values[2], new pnlScsiInfo(scsiInfo, (string)deviceItem.Values[2]) } }); @@ -771,11 +904,12 @@ namespace DiscImageChef.Gui.Forms } else if(((TreeGridItem)e.Item).Values[2] is IReadOnlyFilesystem fsPlugin) { - TreeGridItem fsItem = (TreeGridItem)e.Item; + var fsItem = (TreeGridItem)e.Item; fsItem.Children.Clear(); - if(fsItem.Values.Length == 5 && fsItem.Values[4] is string dirPath) + if(fsItem.Values.Length == 5 && + fsItem.Values[4] is string dirPath) { Errno errno = fsPlugin.ReadDir(dirPath, out List dirents); @@ -783,6 +917,7 @@ namespace DiscImageChef.Gui.Forms { MessageBox.Show($"Error {errno} trying to read \"{dirPath}\" of chosen filesystem", MessageBoxType.Error); + return; } @@ -794,19 +929,24 @@ namespace DiscImageChef.Gui.Forms if(errno != Errno.NoError) { - DicConsole - .ErrorWriteLine($"Error {errno} trying to get information about filesystem entry named {dirent}"); + DicConsole. + ErrorWriteLine($"Error {errno} trying to get information about filesystem entry named {dirent}"); + continue; } - if(stat.Attributes.HasFlag(FileAttributes.Directory)) directories.Add(dirent); + if(stat.Attributes.HasFlag(FileAttributes.Directory)) + directories.Add(dirent); } foreach(string directory in directories) { - TreeGridItem dirItem = new TreeGridItem + var dirItem = new TreeGridItem { - Values = new object[] {imagesIcon, directory, fsPlugin, null, dirPath + "/" + directory} + Values = new object[] + { + imagesIcon, directory, fsPlugin, null, dirPath + "/" + directory + } }; dirItem.Children.Add(placeholderItem); @@ -821,6 +961,7 @@ namespace DiscImageChef.Gui.Forms { MessageBox.Show($"Error {errno} trying to read root directory of chosen filesystem", MessageBoxType.Error); + return; } @@ -833,16 +974,19 @@ namespace DiscImageChef.Gui.Forms if(errno != Errno.NoError) { - DicConsole - .ErrorWriteLine($"Error {errno} trying to get information about filesystem entry named {dirent}"); + DicConsole. + ErrorWriteLine($"Error {errno} trying to get information about filesystem entry named {dirent}"); + continue; } - if(stat.Attributes.HasFlag(FileAttributes.Directory)) directories.Add(dirent); - else files.Add(dirent, stat); + if(stat.Attributes.HasFlag(FileAttributes.Directory)) + directories.Add(dirent); + else + files.Add(dirent, stat); } - TreeGridItem rootDirectoryItem = new TreeGridItem + var rootDirectoryItem = new TreeGridItem { Values = new object[] { @@ -853,9 +997,12 @@ namespace DiscImageChef.Gui.Forms foreach(string directory in directories) { - TreeGridItem dirItem = new TreeGridItem + var dirItem = new TreeGridItem { - Values = new object[] {imagesIcon, directory, fsPlugin, null, "/" + directory} + Values = new object[] + { + imagesIcon, directory, fsPlugin, null, "/" + directory + } }; dirItem.Children.Add(placeholderItem); @@ -868,9 +1015,9 @@ namespace DiscImageChef.Gui.Forms } #region XAML IDs - TreeGridItem devicesRoot; - TreeGridItem imagesRoot; - Splitter splMain; + readonly TreeGridItem devicesRoot; + readonly TreeGridItem imagesRoot; + Splitter splMain; #endregion } } \ No newline at end of file diff --git a/DiscImageChef.Gui/Forms/frmMediaScan.xeto.cs b/DiscImageChef.Gui/Forms/frmMediaScan.xeto.cs index f8ae64577..6d1af3694 100644 --- a/DiscImageChef.Gui/Forms/frmMediaScan.xeto.cs +++ b/DiscImageChef.Gui/Forms/frmMediaScan.xeto.cs @@ -32,7 +32,6 @@ using System; using System.Threading; -using DiscImageChef.CommonTypes; using DiscImageChef.Core; using DiscImageChef.Core.Devices.Scanning; using DiscImageChef.Core.Media.Info; @@ -77,15 +76,9 @@ namespace DiscImageChef.Gui.Forms lineChart.LineColor = Colors.Yellow; } - void OnBtnCancelClick(object sender, EventArgs e) - { - Close(); - } + void OnBtnCancelClick(object sender, EventArgs e) => Close(); - void OnBtnStopClick(object sender, EventArgs e) - { - scanner.Abort(); - } + void OnBtnStopClick(object sender, EventArgs e) => scanner.Abort(); void OnBtnScanClick(object sender, EventArgs e) { @@ -100,10 +93,17 @@ namespace DiscImageChef.Gui.Forms // TODO: Allow to save MHDD and ImgBurn log files void DoWork() { - if(devicePath.Length == 2 && devicePath[1] == ':' && devicePath[0] != '/' && char.IsLetter(devicePath[0])) + if(devicePath.Length == 2 && + devicePath[1] == ':' && + devicePath[0] != '/' && + char.IsLetter(devicePath[0])) devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':'; - Device dev = new Device(devicePath); + var dev = new Device(devicePath); + + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); if(dev.Error) { @@ -137,6 +137,7 @@ namespace DiscImageChef.Gui.Forms { lblTotalTime.Text = lblTotalTime.Text = $"Took a total of {results.TotalTime} seconds ({results.ProcessingTime} processing commands)."; + lblAvgSpeed.Text = $"Average speed: {results.AvgSpeed:F3} MiB/sec."; lblMaxSpeed.Text = $"Fastest speed burst: {results.MaxSpeed:F3} MiB/sec."; lblMinSpeed.Text = $"Slowest speed burst: {results.MinSpeed:F3} MiB/sec."; @@ -171,18 +172,15 @@ namespace DiscImageChef.Gui.Forms WorkFinished(); } - void ScanSpeed(ulong sector, double currentspeed) + void ScanSpeed(ulong sector, double currentspeed) => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => - { - if(currentspeed > lineChart.MaxY) lineChart.MaxY = (float)(currentspeed + currentspeed / 10); + if(currentspeed > lineChart.MaxY) + lineChart.MaxY = (float)(currentspeed + (currentspeed / 10)); - lineChart.Values.Add(new PointF(sector, (float)currentspeed)); - }); - } + lineChart.Values.Add(new PointF(sector, (float)currentspeed)); + }); - void InitBlockMap(ulong blocks, ulong blocksize, ulong blockstoread, ushort currentProfile) - { + void InitBlockMap(ulong blocks, ulong blocksize, ulong blockstoread, ushort currentProfile) => Application.Instance.Invoke(() => { blockMap.Sectors = blocks; @@ -190,6 +188,7 @@ namespace DiscImageChef.Gui.Forms blocksToRead = blockstoread; lineChart.MinX = 0; lineChart.MinY = 0; + switch(currentProfile) { case 0x0005: // CD and DDCD @@ -199,13 +198,19 @@ namespace DiscImageChef.Gui.Forms case 0x0020: case 0x0021: case 0x0022: - if(blocks <= 360000) lineChart.MaxX = 360000; - else if(blocks <= 405000) lineChart.MaxX = 405000; - else if(blocks <= 445500) lineChart.MaxX = 445500; - else lineChart.MaxX = blocks; + if(blocks <= 360000) + lineChart.MaxX = 360000; + else if(blocks <= 405000) + lineChart.MaxX = 405000; + else if(blocks <= 445500) + lineChart.MaxX = 445500; + else + lineChart.MaxX = blocks; + lineChart.StepsX = lineChart.MaxX / 10f; lineChart.StepsY = 150 * 4; lineChart.MaxY = lineChart.StepsY * 12.5f; + break; case 0x0010: // DVD SL case 0x0011: @@ -219,6 +224,7 @@ namespace DiscImageChef.Gui.Forms lineChart.StepsX = lineChart.MaxX / 10f; lineChart.StepsY = 1352.5f; lineChart.MaxY = lineChart.StepsY * 26; + break; case 0x0015: // DVD DL case 0x0016: @@ -229,19 +235,27 @@ namespace DiscImageChef.Gui.Forms lineChart.StepsX = lineChart.MaxX / 10f; lineChart.StepsY = 1352.5f; lineChart.MaxY = lineChart.StepsY * 26; + break; case 0x0041: case 0x0042: case 0x0043: case 0x0040: // BD - if(blocks <= 12219392) lineChart.MaxX = 12219392; - else if(blocks <= 24438784) lineChart.MaxX = 24438784; - else if(blocks <= 48878592) lineChart.MaxX = 48878592; - else if(blocks <= 62500864) lineChart.MaxX = 62500864; - else lineChart.MaxX = blocks; + if(blocks <= 12219392) + lineChart.MaxX = 12219392; + else if(blocks <= 24438784) + lineChart.MaxX = 24438784; + else if(blocks <= 48878592) + lineChart.MaxX = 48878592; + else if(blocks <= 62500864) + lineChart.MaxX = 62500864; + else + lineChart.MaxX = blocks; + lineChart.StepsX = lineChart.MaxX / 10f; lineChart.StepsY = 4394.5f; lineChart.MaxY = lineChart.StepsY * 18; + break; case 0x0050: // HD DVD case 0x0051: @@ -249,145 +263,137 @@ namespace DiscImageChef.Gui.Forms case 0x0053: case 0x0058: case 0x005A: - if(blocks <= 7361599) lineChart.MaxX = 7361599; - else if(blocks <= 16305407) lineChart.MaxX = 16305407; - else lineChart.MaxX = blocks; + if(blocks <= 7361599) + lineChart.MaxX = 7361599; + else if(blocks <= 16305407) + lineChart.MaxX = 16305407; + else + lineChart.MaxX = blocks; + lineChart.StepsX = lineChart.MaxX / 10f; lineChart.StepsY = 4394.5f; lineChart.MaxY = lineChart.StepsY * 8; + break; default: lineChart.MaxX = blocks; lineChart.StepsX = lineChart.MaxX / 10f; lineChart.StepsY = 625f; lineChart.MaxY = lineChart.StepsY; + break; } }); - } - void WorkFinished() + void WorkFinished() => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => + btnStop.Visible = false; + btnScan.Visible = true; + btnCancel.Visible = true; + stkProgress.Visible = false; + lblTotalTime.Visible = true; + lblAvgSpeed.Visible = true; + lblMaxSpeed.Visible = true; + lblMinSpeed.Visible = true; + }); + + void EndProgress() => Application.Instance.Invoke(() => + { + stkProgress1.Visible = false; + }); + + void UpdateProgress(string text, long current, long maximum) => Application.Instance.Invoke(() => + { + lblProgress.Text = text; + prgProgress.Indeterminate = false; + prgProgress.MinValue = 0; + + if(maximum > int.MaxValue) { - btnStop.Visible = false; - btnScan.Visible = true; - btnCancel.Visible = true; - stkProgress.Visible = false; - lblTotalTime.Visible = true; - lblAvgSpeed.Visible = true; - lblMaxSpeed.Visible = true; - lblMinSpeed.Visible = true; - }); - } - - void EndProgress() - { - Application.Instance.Invoke(() => { stkProgress1.Visible = false; }); - } - - void UpdateProgress(string text, long current, long maximum) - { - Application.Instance.Invoke(() => + prgProgress.MaxValue = (int)(maximum / int.MaxValue); + prgProgress.Value = (int)(current / int.MaxValue); + } + else { - lblProgress.Text = text; - prgProgress.Indeterminate = false; - prgProgress.MinValue = 0; - if(maximum > int.MaxValue) - { - prgProgress.MaxValue = (int)(maximum / int.MaxValue); - prgProgress.Value = (int)(current / int.MaxValue); - } - else - { - prgProgress.MaxValue = (int)maximum; - prgProgress.Value = (int)current; - } - }); - } + prgProgress.MaxValue = (int)maximum; + prgProgress.Value = (int)current; + } + }); - void InitProgress() + void InitProgress() => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => { stkProgress1.Visible = true; }); - } + stkProgress1.Visible = true; + }); - void PulseProgress(string text) + void PulseProgress(string text) => Application.Instance.Invoke(() => { - Application.Instance.Invoke(() => + lblProgress.Text = text; + prgProgress.Indeterminate = true; + }); + + void StoppingErrorMessage(string text) => Application.Instance.Invoke(() => + { + lblProgress.Text = text; + MessageBox.Show(text, MessageBoxType.Error); + WorkFinished(); + }); + + void UpdateStatus(string text) => Application.Instance.Invoke(() => + { + lblProgress.Text = text; + }); + + void OnScanUnreadable(ulong sector) => Application.Instance.Invoke(() => + { + localResults.Errored += blocksToRead; + lblUnreadableSectors.Text = $"{localResults.Errored} sectors could not be read."; + blockMap.ColoredSectors.Add(new ColoredBlock(sector, LightGreen)); + }); + + void OnScanTime(ulong sector, double duration) => Application.Instance.Invoke(() => + { + if(duration < 3) { - lblProgress.Text = text; - prgProgress.Indeterminate = true; - }); - } - - void StoppingErrorMessage(string text) - { - Application.Instance.Invoke(() => - { - lblProgress.Text = text; - MessageBox.Show(text, MessageBoxType.Error); - WorkFinished(); - }); - } - - void UpdateStatus(string text) - { - Application.Instance.Invoke(() => { lblProgress.Text = text; }); - } - - void OnScanUnreadable(ulong sector) - { - Application.Instance.Invoke(() => - { - localResults.Errored += blocksToRead; - lblUnreadableSectors.Text = $"{localResults.Errored} sectors could not be read."; + localResults.A += blocksToRead; blockMap.ColoredSectors.Add(new ColoredBlock(sector, LightGreen)); - }); - } - - void OnScanTime(ulong sector, double duration) - { - Application.Instance.Invoke(() => + } + else if(duration >= 3 && + duration < 10) { - if(duration < 3) - { - localResults.A += blocksToRead; - blockMap.ColoredSectors.Add(new ColoredBlock(sector, LightGreen)); - } - else if(duration >= 3 && duration < 10) - { - localResults.B += blocksToRead; - blockMap.ColoredSectors.Add(new ColoredBlock(sector, Green)); - } - else if(duration >= 10 && duration < 50) - { - localResults.C += blocksToRead; - blockMap.ColoredSectors.Add(new ColoredBlock(sector, DarkGreen)); - } - else if(duration >= 50 && duration < 150) - { - localResults.D += blocksToRead; - blockMap.ColoredSectors.Add(new ColoredBlock(sector, Yellow)); - } - else if(duration >= 150 && duration < 500) - { - localResults.E += blocksToRead; - blockMap.ColoredSectors.Add(new ColoredBlock(sector, Orange)); - } - else if(duration >= 500) - { - localResults.F += blocksToRead; - blockMap.ColoredSectors.Add(new ColoredBlock(sector, Red)); - } + localResults.B += blocksToRead; + blockMap.ColoredSectors.Add(new ColoredBlock(sector, Green)); + } + else if(duration >= 10 && + duration < 50) + { + localResults.C += blocksToRead; + blockMap.ColoredSectors.Add(new ColoredBlock(sector, DarkGreen)); + } + else if(duration >= 50 && + duration < 150) + { + localResults.D += blocksToRead; + blockMap.ColoredSectors.Add(new ColoredBlock(sector, Yellow)); + } + else if(duration >= 150 && + duration < 500) + { + localResults.E += blocksToRead; + blockMap.ColoredSectors.Add(new ColoredBlock(sector, Orange)); + } + else if(duration >= 500) + { + localResults.F += blocksToRead; + blockMap.ColoredSectors.Add(new ColoredBlock(sector, Red)); + } - lblA.Text = $"{localResults.A} sectors took less than 3 ms."; - lblB.Text = $"{localResults.B} sectors took less than 10 ms but more than 3 ms."; - lblC.Text = $"{localResults.C} sectors took less than 50 ms but more than 10 ms."; - lblD.Text = $"{localResults.D} sectors took less than 150 ms but more than 50 ms."; - lblE.Text = $"{localResults.E} sectors took less than 500 ms but more than 150 ms."; - lblF.Text = $"{localResults.F} sectors took more than 500 ms."; - }); - } + lblA.Text = $"{localResults.A} sectors took less than 3 ms."; + lblB.Text = $"{localResults.B} sectors took less than 10 ms but more than 3 ms."; + lblC.Text = $"{localResults.C} sectors took less than 50 ms but more than 10 ms."; + lblD.Text = $"{localResults.D} sectors took less than 150 ms but more than 50 ms."; + lblE.Text = $"{localResults.E} sectors took less than 500 ms but more than 150 ms."; + lblF.Text = $"{localResults.F} sectors took more than 500 ms."; + }); #region XAML IDs Label lblTotalTime; diff --git a/DiscImageChef/Commands/DeviceInfo.cs b/DiscImageChef/Commands/DeviceInfo.cs index 5ba398fde..8234fe495 100644 --- a/DiscImageChef/Commands/DeviceInfo.cs +++ b/DiscImageChef/Commands/DeviceInfo.cs @@ -47,51 +47,57 @@ namespace DiscImageChef.Commands { internal class DeviceInfoCommand : Command { - private string devicePath; - private string outputPrefix; + string devicePath; + string outputPrefix; - private bool showHelp; + bool showHelp; - public DeviceInfoCommand() : base("device-info", "Gets information about a device.") + public DeviceInfoCommand() : base("device-info", "Gets information about a device.") => Options = new OptionSet { - Options = new OptionSet + $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}", + $"{MainClass.AssemblyCopyright}", "", $"usage: DiscImageChef {Name} [OPTIONS] devicepath", "", + Help, { - $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}", - $"{MainClass.AssemblyCopyright}", - "", - $"usage: DiscImageChef {Name} [OPTIONS] devicepath", - "", - Help, - {"output-prefix|w=", "Name of character encoding to use.", s => outputPrefix = s}, - {"help|h|?", "Show this message and exit.", v => showHelp = v != null} - }; - } + "output-prefix|w=", "Name of character encoding to use.", s => outputPrefix = s + }, + { + "help|h|?", "Show this message and exit.", v => showHelp = v != null + } + }; public override int Invoke(IEnumerable arguments) { - var extra = Options.Parse(arguments); + List extra = Options.Parse(arguments); - if (showHelp) + if(showHelp) { Options.WriteOptionDescriptions(CommandSet.Out); - return (int) ErrorNumber.HelpRequested; + + return(int)ErrorNumber.HelpRequested; } MainClass.PrintCopyright(); - if (MainClass.Debug) DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; - if (MainClass.Verbose) DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + + if(MainClass.Debug) + DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; + + if(MainClass.Verbose) + DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + Statistics.AddCommand("device-info"); - if (extra.Count > 1) + if(extra.Count > 1) { DicConsole.ErrorWriteLine("Too many arguments."); - return (int) ErrorNumber.UnexpectedArgumentCount; + + return(int)ErrorNumber.UnexpectedArgumentCount; } - if (extra.Count == 0) + if(extra.Count == 0) { DicConsole.ErrorWriteLine("Missing device path."); - return (int) ErrorNumber.MissingArgument; + + return(int)ErrorNumber.MissingArgument; } devicePath = extra[0]; @@ -101,33 +107,45 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Device-Info command", "--output-prefix={0}", outputPrefix); DicConsole.DebugWriteLine("Device-Info command", "--verbose={0}", MainClass.Verbose); - if (devicePath.Length == 2 && devicePath[1] == ':' && devicePath[0] != '/' && char.IsLetter(devicePath[0])) + if(devicePath.Length == 2 && + devicePath[1] == ':' && + devicePath[0] != '/' && + char.IsLetter(devicePath[0])) devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':'; Device dev; + try { dev = new Device(devicePath); - if (dev.Error) + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); + + if(dev.Error) { DicConsole.ErrorWriteLine(Error.Print(dev.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } } - catch (DeviceException e) + catch(DeviceException e) { DicConsole.ErrorWriteLine(e.Message ?? Error.Print(e.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } Statistics.AddDevice(dev); - if (dev.IsUsb) + if(dev.IsUsb) { DicConsole.WriteLine("USB device"); - if (dev.UsbDescriptors != null) + + if(dev.UsbDescriptors != null) DicConsole.WriteLine("USB descriptor is {0} bytes", dev.UsbDescriptors.Length); + DicConsole.WriteLine("USB Vendor ID: {0:X4}", dev.UsbVendorId); DicConsole.WriteLine("USB Product ID: {0:X4}", dev.UsbProductId); DicConsole.WriteLine("USB Manufacturer: {0}", dev.UsbManufacturerString); @@ -136,7 +154,7 @@ namespace DiscImageChef.Commands DicConsole.WriteLine(); } - if (dev.IsFireWire) + if(dev.IsFireWire) { DicConsole.WriteLine("FireWire device"); DicConsole.WriteLine("FireWire Vendor ID: {0:X6}", dev.FireWireVendor); @@ -147,26 +165,30 @@ namespace DiscImageChef.Commands DicConsole.WriteLine(); } - if (dev.IsPcmcia) + if(dev.IsPcmcia) { DicConsole.WriteLine("PCMCIA device"); DicConsole.WriteLine("PCMCIA CIS is {0} bytes", dev.Cis.Length); - var tuples = CIS.GetTuples(dev.Cis); - if (tuples != null) - foreach (var tuple in tuples) - switch (tuple.Code) + Tuple[] tuples = CIS.GetTuples(dev.Cis); + + if(tuples != null) + foreach(Tuple tuple in tuples) + switch(tuple.Code) { case TupleCodes.CISTPL_NULL: case TupleCodes.CISTPL_END: break; case TupleCodes.CISTPL_DEVICEGEO: case TupleCodes.CISTPL_DEVICEGEO_A: DicConsole.WriteLine("{0}", CIS.PrettifyDeviceGeometryTuple(tuple)); + break; case TupleCodes.CISTPL_MANFID: DicConsole.WriteLine("{0}", CIS.PrettifyManufacturerIdentificationTuple(tuple)); + break; case TupleCodes.CISTPL_VERS_1: DicConsole.WriteLine("{0}", CIS.PrettifyLevel1VersionTuple(tuple)); + break; case TupleCodes.CISTPL_ALTSTR: case TupleCodes.CISTPL_BAR: @@ -203,454 +225,551 @@ namespace DiscImageChef.Commands case TupleCodes.CISTPL_SWIL: case TupleCodes.CISTPL_VERS_2: DicConsole.DebugWriteLine("Device-Info command", "Found undecoded tuple ID {0}", - tuple.Code); + tuple.Code); + break; default: DicConsole.DebugWriteLine("Device-Info command", "Found unknown tuple ID 0x{0:X2}", - (byte) tuple.Code); + (byte)tuple.Code); + break; } - else DicConsole.DebugWriteLine("Device-Info command", "Could not get tuples"); + else + DicConsole.DebugWriteLine("Device-Info command", "Could not get tuples"); } var devInfo = new DeviceInfo(dev); - if (devInfo.AtaIdentify != null) + if(devInfo.AtaIdentify != null) { DataFile.WriteTo("Device-Info command", outputPrefix, "_ata_identify.bin", "ATA IDENTIFY", - devInfo.AtaIdentify); + devInfo.AtaIdentify); DicConsole.WriteLine(Identify.Prettify(devInfo.AtaIdentify)); - if (devInfo.AtaMcptError.HasValue) + if(devInfo.AtaMcptError.HasValue) { DicConsole.WriteLine("Device supports the Media Card Pass Through Command Set"); - switch (devInfo.AtaMcptError.Value.DeviceHead & 0x7) + + switch(devInfo.AtaMcptError.Value.DeviceHead & 0x7) { case 0: DicConsole.WriteLine("Device reports incorrect media card type"); + break; case 1: DicConsole.WriteLine("Device contains a Secure Digital card"); + break; case 2: DicConsole.WriteLine("Device contains a MultiMediaCard "); + break; case 3: DicConsole.WriteLine("Device contains a Secure Digital I/O card"); + break; case 4: DicConsole.WriteLine("Device contains a Smart Media card"); + break; default: DicConsole.WriteLine("Device contains unknown media card type {0}", - devInfo.AtaMcptError.Value.DeviceHead & 0x07); + devInfo.AtaMcptError.Value.DeviceHead & 0x07); + break; } - if ((devInfo.AtaMcptError.Value.DeviceHead & 0x08) == 0x08) + if((devInfo.AtaMcptError.Value.DeviceHead & 0x08) == 0x08) DicConsole.WriteLine("Media card is write protected"); - var specificData = (ushort) (devInfo.AtaMcptError.Value.CylinderHigh * 0x100 + - devInfo.AtaMcptError.Value.CylinderLow); - if (specificData != 0) DicConsole.WriteLine("Card specific data: 0x{0:X4}", specificData); + ushort specificData = (ushort)((devInfo.AtaMcptError.Value.CylinderHigh * 0x100) + + devInfo.AtaMcptError.Value.CylinderLow); + + if(specificData != 0) + DicConsole.WriteLine("Card specific data: 0x{0:X4}", specificData); } } - if (devInfo.AtapiIdentify != null) + if(devInfo.AtapiIdentify != null) { DataFile.WriteTo("Device-Info command", outputPrefix, "_atapi_identify.bin", "ATAPI IDENTIFY", - devInfo.AtapiIdentify); + devInfo.AtapiIdentify); DicConsole.WriteLine(Identify.Prettify(devInfo.AtapiIdentify)); } - if (devInfo.ScsiInquiry != null) + if(devInfo.ScsiInquiry != null) { - if (dev.Type != DeviceType.ATAPI) DicConsole.WriteLine("SCSI device"); + if(dev.Type != DeviceType.ATAPI) + DicConsole.WriteLine("SCSI device"); DataFile.WriteTo("Device-Info command", outputPrefix, "_scsi_inquiry.bin", "SCSI INQUIRY", - devInfo.ScsiInquiryData); + devInfo.ScsiInquiryData); DicConsole.WriteLine(Inquiry.Prettify(devInfo.ScsiInquiry)); - if (devInfo.ScsiEvpdPages != null) - foreach (var page in devInfo.ScsiEvpdPages) - if (page.Key >= 0x01 && page.Key <= 0x7F) + if(devInfo.ScsiEvpdPages != null) + foreach(KeyValuePair page in devInfo.ScsiEvpdPages) + if(page.Key >= 0x01 && + page.Key <= 0x7F) { DicConsole.WriteLine("ASCII Page {0:X2}h: {1}", page.Key, EVPD.DecodeASCIIPage(page.Value)); DataFile.WriteTo("Device-Info command", outputPrefix, page.Value); } - else if (page.Key == 0x80) + else if(page.Key == 0x80) { DicConsole.WriteLine("Unit Serial Number: {0}", EVPD.DecodePage80(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0x81) + else if(page.Key == 0x81) { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_81(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0x82) + else if(page.Key == 0x82) { DicConsole.WriteLine("ASCII implemented operating definitions: {0}", - EVPD.DecodePage82(page.Value)); + EVPD.DecodePage82(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0x83) + else if(page.Key == 0x83) { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_83(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0x84) + else if(page.Key == 0x84) { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_84(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0x85) + else if(page.Key == 0x85) { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_85(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0x86) + else if(page.Key == 0x86) { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_86(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0x89) + else if(page.Key == 0x89) { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_89(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xB0) + else if(page.Key == 0xB0) { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_B0(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xB1) + else if(page.Key == 0xB1) { DicConsole.WriteLine("Manufacturer-assigned Serial Number: {0}", - EVPD.DecodePageB1(page.Value)); + EVPD.DecodePageB1(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xB2) + else if(page.Key == 0xB2) { DicConsole.WriteLine("TapeAlert Supported Flags Bitmap: 0x{0:X16}", - EVPD.DecodePageB2(page.Value)); + EVPD.DecodePageB2(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xB3) + else if(page.Key == 0xB3) { DicConsole.WriteLine("Automation Device Serial Number: {0}", EVPD.DecodePageB3(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xB4) + else if(page.Key == 0xB4) { DicConsole.WriteLine("Data Transfer Device Element Address: 0x{0}", - EVPD.DecodePageB4(page.Value)); + EVPD.DecodePageB4(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xC0 && - StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification) - .ToLowerInvariant().Trim() == "quantum") + else if(page.Key == 0xC0 && + StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification). + ToLowerInvariant().Trim() == "quantum") { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_C0_Quantum(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xC0 && - StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification) - .ToLowerInvariant().Trim() == "seagate") + else if(page.Key == 0xC0 && + StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification). + ToLowerInvariant().Trim() == "seagate") { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_C0_Seagate(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xC0 && - StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification) - .ToLowerInvariant().Trim() == "ibm") + else if(page.Key == 0xC0 && + StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification). + ToLowerInvariant().Trim() == "ibm") { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_C0_IBM(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xC1 && - StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification) - .ToLowerInvariant().Trim() == "ibm") + else if(page.Key == 0xC1 && + StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification). + ToLowerInvariant().Trim() == "ibm") { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_C1_IBM(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if ((page.Key == 0xC0 || page.Key == 0xC1) && - StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification) - .ToLowerInvariant().Trim() == "certance") + else if((page.Key == 0xC0 || page.Key == 0xC1) && + StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification). + ToLowerInvariant().Trim() == "certance") { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_C0_C1_Certance(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if ((page.Key == 0xC2 || page.Key == 0xC3 || page.Key == 0xC4 || page.Key == 0xC5 || - page.Key == 0xC6) && - StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification) - .ToLowerInvariant().Trim() == "certance") + else if((page.Key == 0xC2 || page.Key == 0xC3 || page.Key == 0xC4 || page.Key == 0xC5 || + page.Key == 0xC6) && + StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification). + ToLowerInvariant().Trim() == "certance") { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_C2_C3_C4_C5_C6_Certance(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if ((page.Key == 0xC0 || page.Key == 0xC1 || page.Key == 0xC2 || page.Key == 0xC3 || - page.Key == 0xC4 || page.Key == 0xC5) && StringHandlers - .CToString(devInfo.ScsiInquiry.Value - .VendorIdentification) - .ToLowerInvariant().Trim() == "hp") + else if((page.Key == 0xC0 || page.Key == 0xC1 || page.Key == 0xC2 || page.Key == 0xC3 || + page.Key == 0xC4 || page.Key == 0xC5) && + StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification). + ToLowerInvariant().Trim() == "hp") { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_C0_to_C5_HP(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - else if (page.Key == 0xDF && - StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification) - .ToLowerInvariant().Trim() == "certance") + else if(page.Key == 0xDF && + StringHandlers.CToString(devInfo.ScsiInquiry.Value.VendorIdentification). + ToLowerInvariant().Trim() == "certance") { DicConsole.WriteLine("{0}", EVPD.PrettifyPage_DF_Certance(page.Value)); + DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } else { - if (page.Key == 0x00) continue; + if(page.Key == 0x00) + continue; DicConsole.DebugWriteLine("Device-Info command", "Found undecoded SCSI VPD page 0x{0:X2}", - page.Key); + page.Key); DataFile.WriteTo("Device-Info command", outputPrefix, $"_scsi_evpd_{page.Key:X2}h.bin", - $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); + $"SCSI INQUIRY EVPD {page.Key:X2}h", page.Value); } - if (devInfo.ScsiModeSense6 != null) + if(devInfo.ScsiModeSense6 != null) DataFile.WriteTo("Device-Info command", outputPrefix, "_scsi_modesense6.bin", "SCSI MODE SENSE", - devInfo.ScsiModeSense6); + devInfo.ScsiModeSense6); - if (devInfo.ScsiModeSense10 != null) + if(devInfo.ScsiModeSense10 != null) DataFile.WriteTo("Device-Info command", outputPrefix, "_scsi_modesense10.bin", "SCSI MODE SENSE", - devInfo.ScsiModeSense10); + devInfo.ScsiModeSense10); - if (devInfo.ScsiMode.HasValue) + if(devInfo.ScsiMode.HasValue) PrintScsiModePages.Print(devInfo.ScsiMode.Value, - (PeripheralDeviceTypes) devInfo.ScsiInquiry.Value.PeripheralDeviceType, - devInfo.ScsiInquiry.Value.VendorIdentification); + (PeripheralDeviceTypes)devInfo.ScsiInquiry.Value.PeripheralDeviceType, + devInfo.ScsiInquiry.Value.VendorIdentification); - if (devInfo.MmcConfiguration != null) + if(devInfo.MmcConfiguration != null) { DataFile.WriteTo("Device-Info command", outputPrefix, "_mmc_getconfiguration.bin", - "MMC GET CONFIGURATION", devInfo.MmcConfiguration); + "MMC GET CONFIGURATION", devInfo.MmcConfiguration); - var ftr = Features.Separate(devInfo.MmcConfiguration); + Features.SeparatedFeatures ftr = Features.Separate(devInfo.MmcConfiguration); DicConsole.DebugWriteLine("Device-Info command", "GET CONFIGURATION length is {0} bytes", - ftr.DataLength); + ftr.DataLength); + DicConsole.DebugWriteLine("Device-Info command", "GET CONFIGURATION current profile is {0:X4}h", - ftr.CurrentProfile); - if (ftr.Descriptors != null) + ftr.CurrentProfile); + + if(ftr.Descriptors != null) { DicConsole.WriteLine("SCSI MMC GET CONFIGURATION Features:"); - foreach (var desc in ftr.Descriptors) + + foreach(Features.FeatureDescriptor desc in ftr.Descriptors) { DicConsole.DebugWriteLine("Device-Info command", "Feature {0:X4}h", desc.Code); - switch (desc.Code) + switch(desc.Code) { case 0x0000: DicConsole.WriteLine(Features.Prettify_0000(desc.Data)); + break; case 0x0001: DicConsole.WriteLine(Features.Prettify_0001(desc.Data)); + break; case 0x0002: DicConsole.WriteLine(Features.Prettify_0002(desc.Data)); + break; case 0x0003: DicConsole.WriteLine(Features.Prettify_0003(desc.Data)); + break; case 0x0004: DicConsole.WriteLine(Features.Prettify_0004(desc.Data)); + break; case 0x0010: DicConsole.WriteLine(Features.Prettify_0010(desc.Data)); + break; case 0x001D: DicConsole.WriteLine(Features.Prettify_001D(desc.Data)); + break; case 0x001E: DicConsole.WriteLine(Features.Prettify_001E(desc.Data)); + break; case 0x001F: DicConsole.WriteLine(Features.Prettify_001F(desc.Data)); + break; case 0x0020: DicConsole.WriteLine(Features.Prettify_0020(desc.Data)); + break; case 0x0021: DicConsole.WriteLine(Features.Prettify_0021(desc.Data)); + break; case 0x0022: DicConsole.WriteLine(Features.Prettify_0022(desc.Data)); + break; case 0x0023: DicConsole.WriteLine(Features.Prettify_0023(desc.Data)); + break; case 0x0024: DicConsole.WriteLine(Features.Prettify_0024(desc.Data)); + break; case 0x0025: DicConsole.WriteLine(Features.Prettify_0025(desc.Data)); + break; case 0x0026: DicConsole.WriteLine(Features.Prettify_0026(desc.Data)); + break; case 0x0027: DicConsole.WriteLine(Features.Prettify_0027(desc.Data)); + break; case 0x0028: DicConsole.WriteLine(Features.Prettify_0028(desc.Data)); + break; case 0x0029: DicConsole.WriteLine(Features.Prettify_0029(desc.Data)); + break; case 0x002A: DicConsole.WriteLine(Features.Prettify_002A(desc.Data)); + break; case 0x002B: DicConsole.WriteLine(Features.Prettify_002B(desc.Data)); + break; case 0x002C: DicConsole.WriteLine(Features.Prettify_002C(desc.Data)); + break; case 0x002D: DicConsole.WriteLine(Features.Prettify_002D(desc.Data)); + break; case 0x002E: DicConsole.WriteLine(Features.Prettify_002E(desc.Data)); + break; case 0x002F: DicConsole.WriteLine(Features.Prettify_002F(desc.Data)); + break; case 0x0030: DicConsole.WriteLine(Features.Prettify_0030(desc.Data)); + break; case 0x0031: DicConsole.WriteLine(Features.Prettify_0031(desc.Data)); + break; case 0x0032: DicConsole.WriteLine(Features.Prettify_0032(desc.Data)); + break; case 0x0033: DicConsole.WriteLine(Features.Prettify_0033(desc.Data)); + break; case 0x0035: DicConsole.WriteLine(Features.Prettify_0035(desc.Data)); + break; case 0x0037: DicConsole.WriteLine(Features.Prettify_0037(desc.Data)); + break; case 0x0038: DicConsole.WriteLine(Features.Prettify_0038(desc.Data)); + break; case 0x003A: DicConsole.WriteLine(Features.Prettify_003A(desc.Data)); + break; case 0x003B: DicConsole.WriteLine(Features.Prettify_003B(desc.Data)); + break; case 0x0040: DicConsole.WriteLine(Features.Prettify_0040(desc.Data)); + break; case 0x0041: DicConsole.WriteLine(Features.Prettify_0041(desc.Data)); + break; case 0x0042: DicConsole.WriteLine(Features.Prettify_0042(desc.Data)); + break; case 0x0050: DicConsole.WriteLine(Features.Prettify_0050(desc.Data)); + break; case 0x0051: DicConsole.WriteLine(Features.Prettify_0051(desc.Data)); + break; case 0x0080: DicConsole.WriteLine(Features.Prettify_0080(desc.Data)); + break; case 0x0100: DicConsole.WriteLine(Features.Prettify_0100(desc.Data)); + break; case 0x0101: DicConsole.WriteLine(Features.Prettify_0101(desc.Data)); + break; case 0x0102: DicConsole.WriteLine(Features.Prettify_0102(desc.Data)); + break; case 0x0103: DicConsole.WriteLine(Features.Prettify_0103(desc.Data)); + break; case 0x0104: DicConsole.WriteLine(Features.Prettify_0104(desc.Data)); + break; case 0x0105: DicConsole.WriteLine(Features.Prettify_0105(desc.Data)); + break; case 0x0106: DicConsole.WriteLine(Features.Prettify_0106(desc.Data)); + break; case 0x0107: DicConsole.WriteLine(Features.Prettify_0107(desc.Data)); + break; case 0x0108: DicConsole.WriteLine(Features.Prettify_0108(desc.Data)); + break; case 0x0109: DicConsole.WriteLine(Features.Prettify_0109(desc.Data)); + break; case 0x010A: DicConsole.WriteLine(Features.Prettify_010A(desc.Data)); + break; case 0x010B: DicConsole.WriteLine(Features.Prettify_010B(desc.Data)); + break; case 0x010C: DicConsole.WriteLine(Features.Prettify_010C(desc.Data)); + break; case 0x010D: DicConsole.WriteLine(Features.Prettify_010D(desc.Data)); + break; case 0x010E: DicConsole.WriteLine(Features.Prettify_010E(desc.Data)); + break; case 0x0110: DicConsole.WriteLine(Features.Prettify_0110(desc.Data)); + break; case 0x0113: DicConsole.WriteLine(Features.Prettify_0113(desc.Data)); + break; case 0x0142: DicConsole.WriteLine(Features.Prettify_0142(desc.Data)); + break; default: DicConsole.WriteLine("Found unknown feature code {0:X4}h", desc.Code); + break; } } @@ -658,68 +777,73 @@ namespace DiscImageChef.Commands else { DicConsole.DebugWriteLine("Device-Info command", - "GET CONFIGURATION returned no feature descriptors"); + "GET CONFIGURATION returned no feature descriptors"); } } - if (devInfo.PlextorFeatures != null) + if(devInfo.PlextorFeatures != null) { - if (devInfo.PlextorFeatures.Eeprom != null) + if(devInfo.PlextorFeatures.Eeprom != null) { DataFile.WriteTo("Device-Info command", outputPrefix, "_plextor_eeprom.bin", - "PLEXTOR READ EEPROM", devInfo.PlextorFeatures.Eeprom); + "PLEXTOR READ EEPROM", devInfo.PlextorFeatures.Eeprom); DicConsole.WriteLine("Drive has loaded a total of {0} discs", devInfo.PlextorFeatures.Discs); + DicConsole.WriteLine("Drive has spent {0} hours, {1} minutes and {2} seconds reading CDs", - devInfo.PlextorFeatures.CdReadTime / 3600, - devInfo.PlextorFeatures.CdReadTime / 60 % 60, - devInfo.PlextorFeatures.CdReadTime % 60); + devInfo.PlextorFeatures.CdReadTime / 3600, + (devInfo.PlextorFeatures.CdReadTime / 60) % 60, + devInfo.PlextorFeatures.CdReadTime % 60); + DicConsole.WriteLine("Drive has spent {0} hours, {1} minutes and {2} seconds writing CDs", - devInfo.PlextorFeatures.CdWriteTime / 3600, - devInfo.PlextorFeatures.CdWriteTime / 60 % 60, - devInfo.PlextorFeatures.CdWriteTime % 60); - if (devInfo.PlextorFeatures.IsDvd) + devInfo.PlextorFeatures.CdWriteTime / 3600, + (devInfo.PlextorFeatures.CdWriteTime / 60) % 60, + devInfo.PlextorFeatures.CdWriteTime % 60); + + if(devInfo.PlextorFeatures.IsDvd) { DicConsole.WriteLine("Drive has spent {0} hours, {1} minutes and {2} seconds reading DVDs", - devInfo.PlextorFeatures.DvdReadTime / 3600, - devInfo.PlextorFeatures.DvdReadTime / 60 % 60, - devInfo.PlextorFeatures.DvdReadTime % 60); + devInfo.PlextorFeatures.DvdReadTime / 3600, + (devInfo.PlextorFeatures.DvdReadTime / 60) % 60, + devInfo.PlextorFeatures.DvdReadTime % 60); + DicConsole.WriteLine("Drive has spent {0} hours, {1} minutes and {2} seconds writing DVDs", - devInfo.PlextorFeatures.DvdWriteTime / 3600, - devInfo.PlextorFeatures.DvdWriteTime / 60 % 60, - devInfo.PlextorFeatures.DvdWriteTime % 60); + devInfo.PlextorFeatures.DvdWriteTime / 3600, + (devInfo.PlextorFeatures.DvdWriteTime / 60) % 60, + devInfo.PlextorFeatures.DvdWriteTime % 60); } } - if (devInfo.PlextorFeatures.PoweRec) + if(devInfo.PlextorFeatures.PoweRec) { DicConsole.Write("Drive supports PoweRec"); - if (devInfo.PlextorFeatures.PoweRecEnabled) + if(devInfo.PlextorFeatures.PoweRecEnabled) { DicConsole.Write(", has it enabled"); - if (devInfo.PlextorFeatures.PoweRecRecommendedSpeed > 0) + if(devInfo.PlextorFeatures.PoweRecRecommendedSpeed > 0) DicConsole.WriteLine(" and recommends {0} Kb/sec.", - devInfo.PlextorFeatures.PoweRecRecommendedSpeed); - else DicConsole.WriteLine("."); + devInfo.PlextorFeatures.PoweRecRecommendedSpeed); + else + DicConsole.WriteLine("."); - if (devInfo.PlextorFeatures.PoweRecSelected > 0) - DicConsole - .WriteLine( - "Selected PoweRec speed for currently inserted media is {0} Kb/sec ({1}x)", - devInfo.PlextorFeatures.PoweRecSelected, - devInfo.PlextorFeatures.PoweRecSelected / 177); - if (devInfo.PlextorFeatures.PoweRecMax > 0) - DicConsole - .WriteLine( - "Maximum PoweRec speed for currently inserted media is {0} Kb/sec ({1}x)", - devInfo.PlextorFeatures.PoweRecMax, - devInfo.PlextorFeatures.PoweRecMax / 177); - if (devInfo.PlextorFeatures.PoweRecLast > 0) + if(devInfo.PlextorFeatures.PoweRecSelected > 0) + DicConsole. + WriteLine("Selected PoweRec speed for currently inserted media is {0} Kb/sec ({1}x)", + devInfo.PlextorFeatures.PoweRecSelected, + devInfo.PlextorFeatures.PoweRecSelected / 177); + + if(devInfo.PlextorFeatures.PoweRecMax > 0) + DicConsole. + WriteLine("Maximum PoweRec speed for currently inserted media is {0} Kb/sec ({1}x)", + devInfo.PlextorFeatures.PoweRecMax, + devInfo.PlextorFeatures.PoweRecMax / 177); + + if(devInfo.PlextorFeatures.PoweRecLast > 0) DicConsole.WriteLine("Last used PoweRec was {0} Kb/sec ({1}x)", - devInfo.PlextorFeatures.PoweRecLast, - devInfo.PlextorFeatures.PoweRecLast / 177); + devInfo.PlextorFeatures.PoweRecLast, + devInfo.PlextorFeatures.PoweRecLast / 177); } else { @@ -728,111 +852,140 @@ namespace DiscImageChef.Commands } } - if (devInfo.PlextorFeatures.SilentMode) + if(devInfo.PlextorFeatures.SilentMode) { DicConsole.WriteLine("Drive supports Plextor SilentMode"); - if (devInfo.PlextorFeatures.SilentModeEnabled) + + if(devInfo.PlextorFeatures.SilentModeEnabled) { DicConsole.WriteLine("Plextor SilentMode is enabled:"); - DicConsole.WriteLine(devInfo.PlextorFeatures.AccessTimeLimit == 2 - ? "\tAccess time is slow" - : "\tAccess time is fast"); - if (devInfo.PlextorFeatures.CdReadSpeedLimit > 0) + DicConsole.WriteLine(devInfo.PlextorFeatures.AccessTimeLimit == 2 ? "\tAccess time is slow" + : "\tAccess time is fast"); + + if(devInfo.PlextorFeatures.CdReadSpeedLimit > 0) DicConsole.WriteLine("\tCD read speed limited to {0}x", - devInfo.PlextorFeatures.CdReadSpeedLimit); - if (devInfo.PlextorFeatures.DvdReadSpeedLimit > 0 && devInfo.PlextorFeatures.IsDvd) + devInfo.PlextorFeatures.CdReadSpeedLimit); + + if(devInfo.PlextorFeatures.DvdReadSpeedLimit > 0 && + devInfo.PlextorFeatures.IsDvd) DicConsole.WriteLine("\tDVD read speed limited to {0}x", - devInfo.PlextorFeatures.DvdReadSpeedLimit); - if (devInfo.PlextorFeatures.CdWriteSpeedLimit > 0) + devInfo.PlextorFeatures.DvdReadSpeedLimit); + + if(devInfo.PlextorFeatures.CdWriteSpeedLimit > 0) DicConsole.WriteLine("\tCD write speed limited to {0}x", - devInfo.PlextorFeatures.CdWriteSpeedLimit); + devInfo.PlextorFeatures.CdWriteSpeedLimit); } } - if (devInfo.PlextorFeatures.GigaRec) DicConsole.WriteLine("Drive supports Plextor GigaRec"); - if (devInfo.PlextorFeatures.SecuRec) DicConsole.WriteLine("Drive supports Plextor SecuRec"); - if (devInfo.PlextorFeatures.SpeedRead) + if(devInfo.PlextorFeatures.GigaRec) + DicConsole.WriteLine("Drive supports Plextor GigaRec"); + + if(devInfo.PlextorFeatures.SecuRec) + DicConsole.WriteLine("Drive supports Plextor SecuRec"); + + if(devInfo.PlextorFeatures.SpeedRead) { DicConsole.Write("Drive supports Plextor SpeedRead"); - if (devInfo.PlextorFeatures.SpeedReadEnabled) DicConsole.WriteLine("and has it enabled"); - else DicConsole.WriteLine(); + + if(devInfo.PlextorFeatures.SpeedReadEnabled) + DicConsole.WriteLine("and has it enabled"); + else + DicConsole.WriteLine(); } - if (devInfo.PlextorFeatures.Hiding) + if(devInfo.PlextorFeatures.Hiding) { DicConsole.WriteLine("Drive supports hiding CD-Rs and forcing single session"); - if (devInfo.PlextorFeatures.HidesRecordables) + if(devInfo.PlextorFeatures.HidesRecordables) DicConsole.WriteLine("Drive currently hides CD-Rs"); - if (devInfo.PlextorFeatures.HidesSessions) + + if(devInfo.PlextorFeatures.HidesSessions) DicConsole.WriteLine("Drive currently forces single session"); } - if (devInfo.PlextorFeatures.VariRec) DicConsole.WriteLine("Drive supports Plextor VariRec"); + if(devInfo.PlextorFeatures.VariRec) + DicConsole.WriteLine("Drive supports Plextor VariRec"); - if (devInfo.PlextorFeatures.IsDvd) + if(devInfo.PlextorFeatures.IsDvd) { - if (devInfo.PlextorFeatures.VariRecDvd) + if(devInfo.PlextorFeatures.VariRecDvd) DicConsole.WriteLine("Drive supports Plextor VariRec for DVDs"); - if (devInfo.PlextorFeatures.BitSetting) + + if(devInfo.PlextorFeatures.BitSetting) DicConsole.WriteLine("Drive supports bitsetting DVD+R book type"); - if (devInfo.PlextorFeatures.BitSettingDl) + + if(devInfo.PlextorFeatures.BitSettingDl) DicConsole.WriteLine("Drive supports bitsetting DVD+R DL book type"); - if (devInfo.PlextorFeatures.DvdPlusWriteTest) + + if(devInfo.PlextorFeatures.DvdPlusWriteTest) DicConsole.WriteLine("Drive supports test writing DVD+"); } } - if (devInfo.ScsiInquiry.Value.KreonPresent) + if(devInfo.ScsiInquiry.Value.KreonPresent) { DicConsole.WriteLine("Drive has kreon firmware:"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.ChallengeResponse)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.ChallengeResponse)) DicConsole.WriteLine("\tCan do challenge/response with Xbox discs"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.DecryptSs)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.DecryptSs)) DicConsole.WriteLine("\tCan read and descrypt SS from Xbox discs"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.XtremeUnlock)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.XtremeUnlock)) DicConsole.WriteLine("\tCan set xtreme unlock state with Xbox discs"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.WxripperUnlock)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.WxripperUnlock)) DicConsole.WriteLine("\tCan set wxripper unlock state with Xbox discs"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.ChallengeResponse360)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.ChallengeResponse360)) DicConsole.WriteLine("\tCan do challenge/response with Xbox 360 discs"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.DecryptSs360)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.DecryptSs360)) DicConsole.WriteLine("\tCan read and descrypt SS from Xbox 360 discs"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.XtremeUnlock360)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.XtremeUnlock360)) DicConsole.WriteLine("\tCan set xtreme unlock state with Xbox 360 discs"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.WxripperUnlock360)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.WxripperUnlock360)) DicConsole.WriteLine("\tCan set wxripper unlock state with Xbox 360 discs"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.Lock)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.Lock)) DicConsole.WriteLine("\tCan set locked state"); - if (devInfo.KreonFeatures.HasFlag(KreonFeatures.ErrorSkipping)) + + if(devInfo.KreonFeatures.HasFlag(KreonFeatures.ErrorSkipping)) DicConsole.WriteLine("\tCan skip read errors"); } - if (devInfo.BlockLimits != null) + if(devInfo.BlockLimits != null) { DataFile.WriteTo("Device-Info command", outputPrefix, "_ssc_readblocklimits.bin", - "SSC READ BLOCK LIMITS", devInfo.BlockLimits); + "SSC READ BLOCK LIMITS", devInfo.BlockLimits); + DicConsole.WriteLine("Block limits for device:"); DicConsole.WriteLine(BlockLimits.Prettify(devInfo.BlockLimits)); } - if (devInfo.DensitySupport != null) + if(devInfo.DensitySupport != null) { DataFile.WriteTo("Device-Info command", outputPrefix, "_ssc_reportdensitysupport.bin", - "SSC REPORT DENSITY SUPPORT", devInfo.DensitySupport); - if (devInfo.DensitySupportHeader.HasValue) + "SSC REPORT DENSITY SUPPORT", devInfo.DensitySupport); + + if(devInfo.DensitySupportHeader.HasValue) { DicConsole.WriteLine("Densities supported by device:"); DicConsole.WriteLine(DensitySupport.PrettifyDensity(devInfo.DensitySupportHeader)); } } - if (devInfo.MediumDensitySupport != null) + if(devInfo.MediumDensitySupport != null) { DataFile.WriteTo("Device-Info command", outputPrefix, "_ssc_reportdensitysupport_medium.bin", - "SSC REPORT DENSITY SUPPORT (MEDIUM)", devInfo.MediumDensitySupport); - if (devInfo.MediaTypeSupportHeader.HasValue) + "SSC REPORT DENSITY SUPPORT (MEDIUM)", devInfo.MediumDensitySupport); + + if(devInfo.MediaTypeSupportHeader.HasValue) { DicConsole.WriteLine("Medium types supported by device:"); DicConsole.WriteLine(DensitySupport.PrettifyMediumType(devInfo.MediaTypeSupportHeader)); @@ -842,87 +995,102 @@ namespace DiscImageChef.Commands } } - switch (dev.Type) + switch(dev.Type) { case DeviceType.MMC: { - var noInfo = true; + bool noInfo = true; - if (devInfo.CID != null) + if(devInfo.CID != null) { noInfo = false; DataFile.WriteTo("Device-Info command", outputPrefix, "_mmc_cid.bin", "MMC CID", devInfo.CID); DicConsole.WriteLine("{0}", Decoders.MMC.Decoders.PrettifyCID(devInfo.CID)); } - if (devInfo.CSD != null) + if(devInfo.CSD != null) { noInfo = false; DataFile.WriteTo("Device-Info command", outputPrefix, "_mmc_csd.bin", "MMC CSD", devInfo.CSD); DicConsole.WriteLine("{0}", Decoders.MMC.Decoders.PrettifyCSD(devInfo.CSD)); } - if (devInfo.OCR != null) + if(devInfo.OCR != null) { noInfo = false; DataFile.WriteTo("Device-Info command", outputPrefix, "_mmc_ocr.bin", "MMC OCR", devInfo.OCR); DicConsole.WriteLine("{0}", Decoders.MMC.Decoders.PrettifyOCR(devInfo.OCR)); } - if (devInfo.ExtendedCSD != null) + if(devInfo.ExtendedCSD != null) { noInfo = false; + DataFile.WriteTo("Device-Info command", outputPrefix, "_mmc_ecsd.bin", "MMC Extended CSD", - devInfo.ExtendedCSD); + devInfo.ExtendedCSD); + DicConsole.WriteLine("{0}", Decoders.MMC.Decoders.PrettifyExtendedCSD(devInfo.ExtendedCSD)); } - if (noInfo) DicConsole.WriteLine("Could not get any kind of information from the device !!!"); + if(noInfo) + DicConsole.WriteLine("Could not get any kind of information from the device !!!"); } + break; case DeviceType.SecureDigital: { - var noInfo = true; + bool noInfo = true; - if (devInfo.CID != null) + if(devInfo.CID != null) { noInfo = false; + DataFile.WriteTo("Device-Info command", outputPrefix, "_sd_cid.bin", "SecureDigital CID", - devInfo.CID); + devInfo.CID); + DicConsole.WriteLine("{0}", Decoders.SecureDigital.Decoders.PrettifyCID(devInfo.CID)); } - if (devInfo.CSD != null) + if(devInfo.CSD != null) { noInfo = false; + DataFile.WriteTo("Device-Info command", outputPrefix, "_sd_csd.bin", "SecureDigital CSD", - devInfo.CSD); + devInfo.CSD); + DicConsole.WriteLine("{0}", Decoders.SecureDigital.Decoders.PrettifyCSD(devInfo.CSD)); } - if (devInfo.OCR != null) + if(devInfo.OCR != null) { noInfo = false; + DataFile.WriteTo("Device-Info command", outputPrefix, "_sd_ocr.bin", "SecureDigital OCR", - devInfo.OCR); + devInfo.OCR); + DicConsole.WriteLine("{0}", Decoders.SecureDigital.Decoders.PrettifyOCR(devInfo.OCR)); } - if (devInfo.SCR != null) + if(devInfo.SCR != null) { noInfo = false; + DataFile.WriteTo("Device-Info command", outputPrefix, "_sd_scr.bin", "SecureDigital SCR", - devInfo.SCR); + devInfo.SCR); + DicConsole.WriteLine("{0}", Decoders.SecureDigital.Decoders.PrettifySCR(devInfo.SCR)); } - if (noInfo) DicConsole.WriteLine("Could not get any kind of information from the device !!!"); + if(noInfo) + DicConsole.WriteLine("Could not get any kind of information from the device !!!"); } + break; } dev.Close(); - return (int) ErrorNumber.NoError; + + return(int)ErrorNumber.NoError; } } } \ No newline at end of file diff --git a/DiscImageChef/Commands/DeviceReport.cs b/DiscImageChef/Commands/DeviceReport.cs index 2355ac128..6aa284064 100644 --- a/DiscImageChef/Commands/DeviceReport.cs +++ b/DiscImageChef/Commands/DeviceReport.cs @@ -54,50 +54,55 @@ namespace DiscImageChef.Commands { internal class DeviceReportCommand : Command { - private string devicePath; + string devicePath; - private bool showHelp; + bool showHelp; public DeviceReportCommand() : base("device-report", - "Tests the device capabilities and creates an JSON report of them.") - { + "Tests the device capabilities and creates an JSON report of them.") => Options = new OptionSet { $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}", - $"{MainClass.AssemblyCopyright}", - "", - $"usage: DiscImageChef {Name} devicepath", - "", + $"{MainClass.AssemblyCopyright}", "", $"usage: DiscImageChef {Name} devicepath", "", Help, - {"help|h|?", "Show this message and exit.", v => showHelp = v != null} + { + "help|h|?", "Show this message and exit.", v => showHelp = v != null + } }; - } public override int Invoke(IEnumerable arguments) { - var extra = Options.Parse(arguments); + List extra = Options.Parse(arguments); - if (showHelp) + if(showHelp) { Options.WriteOptionDescriptions(CommandSet.Out); - return (int) ErrorNumber.HelpRequested; + + return(int)ErrorNumber.HelpRequested; } MainClass.PrintCopyright(); - if (MainClass.Debug) DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; - if (MainClass.Verbose) DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + + if(MainClass.Debug) + DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; + + if(MainClass.Verbose) + DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + Statistics.AddCommand("device-report"); - if (extra.Count > 1) + if(extra.Count > 1) { DicConsole.ErrorWriteLine("Too many arguments."); - return (int) ErrorNumber.UnexpectedArgumentCount; + + return(int)ErrorNumber.UnexpectedArgumentCount; } - if (extra.Count == 0) + if(extra.Count == 0) { DicConsole.ErrorWriteLine("Missing device path."); - return (int) ErrorNumber.MissingArgument; + + return(int)ErrorNumber.MissingArgument; } devicePath = extra[0]; @@ -106,57 +111,72 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Device-Report command", "--device={0}", devicePath); DicConsole.DebugWriteLine("Device-Report command", "--verbose={0}", MainClass.Verbose); - if (devicePath.Length == 2 && devicePath[1] == ':' && devicePath[0] != '/' && char.IsLetter(devicePath[0])) + if(devicePath.Length == 2 && + devicePath[1] == ':' && + devicePath[0] != '/' && + char.IsLetter(devicePath[0])) devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':'; Device dev; + try { dev = new Device(devicePath); - if (dev.Error) + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); + + if(dev.Error) { DicConsole.ErrorWriteLine(Error.Print(dev.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } } - catch (DeviceException e) + catch(DeviceException e) { DicConsole.ErrorWriteLine(e.Message ?? Error.Print(e.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } Statistics.AddDevice(dev); bool isAdmin; - if (dev.IsRemote) + if(dev.IsRemote) isAdmin = dev.IsRemoteAdmin; - else isAdmin = DetectOS.IsAdmin; + else + isAdmin = DetectOS.IsAdmin; - if (!isAdmin) + if(!isAdmin) { - DicConsole - .ErrorWriteLine( - "Because of the commands sent to a device, device report must be run with administrative privileges."); - DicConsole.ErrorWriteLine("Not continuing."); - return (int) ErrorNumber.NotEnoughPermissions; - } + DicConsole. + ErrorWriteLine("Because of the commands sent to a device, device report must be run with administrative privileges."); + DicConsole.ErrorWriteLine("Not continuing."); + + return(int)ErrorNumber.NotEnoughPermissions; + } var report = new DeviceReportV2 { Manufacturer = dev.Manufacturer, Model = dev.Model, Revision = dev.Revision, Type = dev.Type }; - var removable = false; + + bool removable = false; string jsonFile; - if (!string.IsNullOrWhiteSpace(dev.Manufacturer) && !string.IsNullOrWhiteSpace(dev.Revision)) + if(!string.IsNullOrWhiteSpace(dev.Manufacturer) && + !string.IsNullOrWhiteSpace(dev.Revision)) jsonFile = dev.Manufacturer + "_" + dev.Model + "_" + dev.Revision + ".json"; - else if (!string.IsNullOrWhiteSpace(dev.Manufacturer)) + else if(!string.IsNullOrWhiteSpace(dev.Manufacturer)) jsonFile = dev.Manufacturer + "_" + dev.Model + ".json"; - else if (!string.IsNullOrWhiteSpace(dev.Revision)) jsonFile = dev.Model + "_" + dev.Revision + ".json"; - else jsonFile = dev.Model + ".json"; + else if(!string.IsNullOrWhiteSpace(dev.Revision)) + jsonFile = dev.Model + "_" + dev.Revision + ".json"; + else + jsonFile = dev.Model + ".json"; jsonFile = jsonFile.Replace('\\', '_').Replace('/', '_').Replace('?', '_'); @@ -164,22 +184,26 @@ namespace DiscImageChef.Commands ConsoleKeyInfo pressedKey; - if (dev.IsUsb) + if(dev.IsUsb) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Is the device natively USB (in case of doubt, press Y)? (Y/N): "); pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } - if (pressedKey.Key == ConsoleKey.Y) + if(pressedKey.Key == ConsoleKey.Y) { report.USB = reporter.UsbReport(); pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Is the media removable from the reading/writing elements? (Y/N): "); pressedKey = System.Console.ReadKey(); @@ -187,26 +211,30 @@ namespace DiscImageChef.Commands } report.USB.RemovableMedia = pressedKey.Key == ConsoleKey.Y; - removable = report.USB.RemovableMedia; + removable = report.USB.RemovableMedia; } } - if (dev.IsFireWire) + if(dev.IsFireWire) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Is the device natively FireWire (in case of doubt, press Y)? (Y/N): "); pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } - if (pressedKey.Key != ConsoleKey.Y) + if(pressedKey.Key != ConsoleKey.Y) { report.FireWire = reporter.FireWireReport(); pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Is the media removable from the reading/writing elements? (Y/N): "); pressedKey = System.Console.ReadKey(); @@ -214,17 +242,18 @@ namespace DiscImageChef.Commands } report.FireWire.RemovableMedia = pressedKey.Key == ConsoleKey.Y; - removable = report.FireWire.RemovableMedia; + removable = report.FireWire.RemovableMedia; } } - if (dev.IsPcmcia) report.PCMCIA = reporter.PcmciaReport(); + if(dev.IsPcmcia) + report.PCMCIA = reporter.PcmciaReport(); byte[] buffer; string mediumTypeName; string mediumModel; - switch (dev.Type) + switch(dev.Type) { case DeviceType.ATA: { @@ -232,23 +261,30 @@ namespace DiscImageChef.Commands dev.AtaIdentify(out buffer, out _, dev.Timeout, out _); - if (!Identify.Decode(buffer).HasValue) break; + if(!Identify.Decode(buffer).HasValue) + break; - report.ATA = new Ata {Identify = DeviceReport.ClearIdentify(buffer)}; + report.ATA = new Ata + { + Identify = DeviceReport.ClearIdentify(buffer) + }; - if (report.ATA.IdentifyDevice == null) break; + if(report.ATA.IdentifyDevice == null) + break; - if ((ushort) report.ATA.IdentifyDevice?.GeneralConfiguration == 0x848A) + if((ushort)report.ATA.IdentifyDevice?.GeneralConfiguration == 0x848A) { report.CompactFlash = true; - removable = false; + removable = false; } - else if (!removable && - report.ATA.IdentifyDevice?.GeneralConfiguration.HasFlag(Identify.GeneralConfigurationBit - .Removable) == true) + else if(!removable && + report.ATA.IdentifyDevice?.GeneralConfiguration.HasFlag(Identify.GeneralConfigurationBit. + Removable) == true) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Is the media removable from the reading/writing elements? (Y/N): "); pressedKey = System.Console.ReadKey(); @@ -258,28 +294,33 @@ namespace DiscImageChef.Commands removable = pressedKey.Key == ConsoleKey.Y; } - if (removable) + if(removable) { - DicConsole - .WriteLine("Please remove any media from the device and press any key when it is out."); + DicConsole. + WriteLine("Please remove any media from the device and press any key when it is out."); + System.Console.ReadKey(true); DicConsole.WriteLine("Querying ATA IDENTIFY..."); dev.AtaIdentify(out buffer, out _, dev.Timeout, out _); report.ATA.Identify = DeviceReport.ClearIdentify(buffer); - var mediaTests = new List(); + List mediaTests = new List(); pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.N) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Do you have media that you can insert in the drive? (Y/N): "); pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } - if (pressedKey.Key != ConsoleKey.Y) continue; + if(pressedKey.Key != ConsoleKey.Y) + continue; DicConsole.WriteLine("Please insert it in the drive and press any key when it is ready."); System.Console.ReadKey(true); @@ -289,9 +330,9 @@ namespace DiscImageChef.Commands DicConsole.Write("Please write the media model and press enter: "); mediumModel = System.Console.ReadLine(); - var mediaTest = reporter.ReportAtaMedia(); + TestedMedia mediaTest = reporter.ReportAtaMedia(); mediaTest.MediumTypeName = mediumTypeName; - mediaTest.Model = mediumModel; + mediaTest.Model = mediumModel; mediaTests.Add(mediaTest); } @@ -308,9 +349,11 @@ namespace DiscImageChef.Commands case DeviceType.MMC: report.MultiMediaCard = reporter.MmcSdReport(); + break; case DeviceType.SecureDigital: report.SecureDigital = reporter.MmcSdReport(); + break; case DeviceType.NVMe: throw new NotImplementedException("NVMe devices not yet supported."); case DeviceType.ATAPI: @@ -318,19 +361,26 @@ namespace DiscImageChef.Commands dev.AtapiIdentify(out buffer, out _, dev.Timeout, out _); - if (Identify.Decode(buffer).HasValue) - report.ATAPI = new Ata {Identify = DeviceReport.ClearIdentify(buffer)}; + if(Identify.Decode(buffer).HasValue) + report.ATAPI = new Ata + { + Identify = DeviceReport.ClearIdentify(buffer) + }; goto case DeviceType.SCSI; case DeviceType.SCSI: - if (!dev.IsUsb && !dev.IsFireWire && dev.IsRemovable) + if(!dev.IsUsb && + !dev.IsFireWire && + dev.IsRemovable) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { - DicConsole - .Write( - "Is the media removable from the reading/writing elements (flash memories ARE NOT removable)? (Y/N): "); + DicConsole. + Write("Is the media removable from the reading/writing elements (flash memories ARE NOT removable)? (Y/N): "); + pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } @@ -338,172 +388,234 @@ namespace DiscImageChef.Commands removable = pressedKey.Key == ConsoleKey.Y; } - if (removable) + if(removable) { - switch (dev.ScsiType) + switch(dev.ScsiType) { case PeripheralDeviceTypes.MultiMediaDevice: dev.AllowMediumRemoval(out buffer, dev.Timeout, out _); dev.EjectTray(out buffer, dev.Timeout, out _); + break; case PeripheralDeviceTypes.SequentialAccess: dev.SpcAllowMediumRemoval(out buffer, dev.Timeout, out _); DicConsole.WriteLine("Asking drive to unload tape (can take a few minutes)..."); dev.Unload(out buffer, dev.Timeout, out _); + break; } - DicConsole - .WriteLine("Please remove any media from the device and press any key when it is out."); + DicConsole. + WriteLine("Please remove any media from the device and press any key when it is out."); + System.Console.ReadKey(true); } report.SCSI = reporter.ReportScsiInquiry(); - if (report.SCSI == null) break; + + if(report.SCSI == null) + break; report.SCSI.EVPDPages = - reporter.ReportEvpdPages(StringHandlers - .CToString(report.SCSI.Inquiry?.VendorIdentification)?.Trim() - .ToLowerInvariant()); + reporter.ReportEvpdPages(StringHandlers. + CToString(report.SCSI.Inquiry?.VendorIdentification)?.Trim(). + ToLowerInvariant()); - reporter.ReportScsiModes(ref report, out var cdromMode); + reporter.ReportScsiModes(ref report, out byte[] cdromMode); string mediumManufacturer; byte[] senseBuffer; - bool sense; + bool sense; - switch (dev.ScsiType) + switch(dev.ScsiType) { case PeripheralDeviceTypes.MultiMediaDevice: { - var iomegaRev = dev.Manufacturer.ToLowerInvariant() == "iomega" && - dev.Model.ToLowerInvariant().StartsWith("rrd"); + bool iomegaRev = dev.Manufacturer.ToLowerInvariant() == "iomega" && + dev.Model.ToLowerInvariant().StartsWith("rrd"); - var mediaTypes = new List(); + List mediaTypes = new List(); report.SCSI.MultiMediaDevice = new Mmc { ModeSense2AData = cdromMode, Features = reporter.ReportMmcFeatures() }; - if (cdromMode != null && !iomegaRev) + if(cdromMode != null && + !iomegaRev) { mediaTypes.Add("CD-ROM"); mediaTypes.Add("Audio CD"); mediaTypes.Add("Enhanced CD (aka E-CD, CD-Plus or CD+)"); - if (report.SCSI.MultiMediaDevice.ModeSense2A.ReadCDR) mediaTypes.Add("CD-R"); - if (report.SCSI.MultiMediaDevice.ModeSense2A.ReadCDRW) + + if(report.SCSI.MultiMediaDevice.ModeSense2A.ReadCDR) + mediaTypes.Add("CD-R"); + + if(report.SCSI.MultiMediaDevice.ModeSense2A.ReadCDRW) { mediaTypes.Add("CD-RW Ultra Speed (marked 16x or higher)"); mediaTypes.Add("CD-RW High Speed (marked between 8x and 12x)"); mediaTypes.Add("CD-RW (marked 4x or lower)"); } - if (report.SCSI.MultiMediaDevice.ModeSense2A.ReadDVDROM) mediaTypes.Add("DVD-ROM"); - if (report.SCSI.MultiMediaDevice.ModeSense2A.ReadDVDRAM) + if(report.SCSI.MultiMediaDevice.ModeSense2A.ReadDVDROM) + mediaTypes.Add("DVD-ROM"); + + if(report.SCSI.MultiMediaDevice.ModeSense2A.ReadDVDRAM) { mediaTypes.Add("DVD-RAM (1st gen, marked 2.6Gb or 5.2Gb)"); mediaTypes.Add("DVD-RAM (2nd gen, marked 4.7Gb or 9.4Gb)"); } - if (report.SCSI.MultiMediaDevice.ModeSense2A.ReadDVDR) mediaTypes.Add("DVD-R"); + if(report.SCSI.MultiMediaDevice.ModeSense2A.ReadDVDR) + mediaTypes.Add("DVD-R"); } - if (report.SCSI.MultiMediaDevice.Features != null && !iomegaRev) + if(report.SCSI.MultiMediaDevice.Features != null && + !iomegaRev) { - if (report.SCSI.MultiMediaDevice.Features.CanReadBD || - report.SCSI.MultiMediaDevice.Features.CanReadBDR || - report.SCSI.MultiMediaDevice.Features.CanReadBDRE1 || - report.SCSI.MultiMediaDevice.Features.CanReadBDRE2 || - report.SCSI.MultiMediaDevice.Features.CanReadBDROM || - report.SCSI.MultiMediaDevice.Features.CanReadOldBDR || - report.SCSI.MultiMediaDevice.Features.CanReadOldBDRE || - report.SCSI.MultiMediaDevice.Features.CanReadOldBDROM) + if(report.SCSI.MultiMediaDevice.Features.CanReadBD || + report.SCSI.MultiMediaDevice.Features.CanReadBDR || + report.SCSI.MultiMediaDevice.Features.CanReadBDRE1 || + report.SCSI.MultiMediaDevice.Features.CanReadBDRE2 || + report.SCSI.MultiMediaDevice.Features.CanReadBDROM || + report.SCSI.MultiMediaDevice.Features.CanReadOldBDR || + report.SCSI.MultiMediaDevice.Features.CanReadOldBDRE || + report.SCSI.MultiMediaDevice.Features.CanReadOldBDROM) { - if (!mediaTypes.Contains("BD-ROM")) mediaTypes.Add("BD-ROM"); - if (!mediaTypes.Contains("BD-R HTL (not LTH)")) + if(!mediaTypes.Contains("BD-ROM")) + mediaTypes.Add("BD-ROM"); + + if(!mediaTypes.Contains("BD-R HTL (not LTH)")) mediaTypes.Add("BD-R HTL (not LTH)"); - if (!mediaTypes.Contains("BD-RE")) mediaTypes.Add("BD-RE"); - if (!mediaTypes.Contains("BD-R LTH")) mediaTypes.Add("BD-R LTH"); - if (!mediaTypes.Contains("BD-R Triple Layer (100Gb)")) + + if(!mediaTypes.Contains("BD-RE")) + mediaTypes.Add("BD-RE"); + + if(!mediaTypes.Contains("BD-R LTH")) + mediaTypes.Add("BD-R LTH"); + + if(!mediaTypes.Contains("BD-R Triple Layer (100Gb)")) mediaTypes.Add("BD-R Triple Layer (100Gb)"); - if (!mediaTypes.Contains("BD-R Quad Layer (128Gb)")) + + if(!mediaTypes.Contains("BD-R Quad Layer (128Gb)")) mediaTypes.Add("BD-R Quad Layer (128Gb)"); - if (!mediaTypes.Contains("Ultra HD Blu-ray movie")) + + if(!mediaTypes.Contains("Ultra HD Blu-ray movie")) mediaTypes.Add("Ultra HD Blu-ray movie"); - if (!mediaTypes.Contains("PlayStation 3 game")) + + if(!mediaTypes.Contains("PlayStation 3 game")) mediaTypes.Add("PlayStation 3 game"); - if (!mediaTypes.Contains("PlayStation 4 game")) + + if(!mediaTypes.Contains("PlayStation 4 game")) mediaTypes.Add("PlayStation 4 game"); - if (!mediaTypes.Contains("Xbox One game")) mediaTypes.Add("Xbox One game"); - if (!mediaTypes.Contains("Nintendo Wii U game")) + + if(!mediaTypes.Contains("Xbox One game")) + mediaTypes.Add("Xbox One game"); + + if(!mediaTypes.Contains("Nintendo Wii U game")) mediaTypes.Add("Nintendo Wii U game"); } - if (report.SCSI.MultiMediaDevice.Features.CanReadCD || - report.SCSI.MultiMediaDevice.Features.MultiRead) + if(report.SCSI.MultiMediaDevice.Features.CanReadCD || + report.SCSI.MultiMediaDevice.Features.MultiRead) { - if (!mediaTypes.Contains("CD-ROM")) mediaTypes.Add("CD-ROM"); - if (!mediaTypes.Contains("Audio CD")) mediaTypes.Add("Audio CD"); - if (!mediaTypes.Contains("Enhanced CD (aka E-CD, CD-Plus or CD+)")) + if(!mediaTypes.Contains("CD-ROM")) + mediaTypes.Add("CD-ROM"); + + if(!mediaTypes.Contains("Audio CD")) + mediaTypes.Add("Audio CD"); + + if(!mediaTypes.Contains("Enhanced CD (aka E-CD, CD-Plus or CD+)")) mediaTypes.Add("Enhanced CD (aka E-CD, CD-Plus or CD+)"); - if (!mediaTypes.Contains("CD-R")) mediaTypes.Add("CD-R"); - if (!mediaTypes.Contains("CD-RW Ultra Speed (marked 16x or higher)")) + + if(!mediaTypes.Contains("CD-R")) + mediaTypes.Add("CD-R"); + + if(!mediaTypes.Contains("CD-RW Ultra Speed (marked 16x or higher)")) mediaTypes.Add("CD-RW Ultra Speed (marked 16x or higher)"); - if (!mediaTypes.Contains("CD-RW High Speed (marked between 8x and 12x)")) + + if(!mediaTypes.Contains("CD-RW High Speed (marked between 8x and 12x)")) mediaTypes.Add("CD-RW High Speed (marked between 8x and 12x)"); - if (!mediaTypes.Contains("CD-RW (marked 4x or lower)")) + + if(!mediaTypes.Contains("CD-RW (marked 4x or lower)")) mediaTypes.Add("CD-RW (marked 4x or lower)"); } - if (report.SCSI.MultiMediaDevice.Features.CanReadCDMRW) - if (!mediaTypes.Contains("CD-MRW")) + if(report.SCSI.MultiMediaDevice.Features.CanReadCDMRW) + if(!mediaTypes.Contains("CD-MRW")) mediaTypes.Add("CD-MRW"); - if (report.SCSI.MultiMediaDevice.Features.CanReadDDCD) + if(report.SCSI.MultiMediaDevice.Features.CanReadDDCD) { - if (!mediaTypes.Contains("DDCD-ROM")) mediaTypes.Add("DDCD-ROM"); - if (!mediaTypes.Contains("DDCD-R")) mediaTypes.Add("DDCD-R"); - if (!mediaTypes.Contains("DDCD-RW")) mediaTypes.Add("DDCD-RW"); + if(!mediaTypes.Contains("DDCD-ROM")) + mediaTypes.Add("DDCD-ROM"); + + if(!mediaTypes.Contains("DDCD-R")) + mediaTypes.Add("DDCD-R"); + + if(!mediaTypes.Contains("DDCD-RW")) + mediaTypes.Add("DDCD-RW"); } - if (report.SCSI.MultiMediaDevice.Features.CanReadDVD || - report.SCSI.MultiMediaDevice.Features.DVDMultiRead || - report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusR || - report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusRDL || - report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusRW || - report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusRWDL) + if(report.SCSI.MultiMediaDevice.Features.CanReadDVD || + report.SCSI.MultiMediaDevice.Features.DVDMultiRead || + report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusR || + report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusRDL || + report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusRW || + report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusRWDL) { - if (!mediaTypes.Contains("DVD-ROM")) mediaTypes.Add("DVD-ROM"); - if (!mediaTypes.Contains("DVD-R")) mediaTypes.Add("DVD-R"); - if (!mediaTypes.Contains("DVD-RW")) mediaTypes.Add("DVD-RW"); - if (!mediaTypes.Contains("DVD+R")) mediaTypes.Add("DVD+R"); - if (!mediaTypes.Contains("DVD+RW")) mediaTypes.Add("DVD+RW"); - if (!mediaTypes.Contains("DVD-R DL")) mediaTypes.Add("DVD-R DL"); - if (!mediaTypes.Contains("DVD+R DL")) mediaTypes.Add("DVD+R DL"); - if (!mediaTypes.Contains("Nintendo GameCube game")) + if(!mediaTypes.Contains("DVD-ROM")) + mediaTypes.Add("DVD-ROM"); + + if(!mediaTypes.Contains("DVD-R")) + mediaTypes.Add("DVD-R"); + + if(!mediaTypes.Contains("DVD-RW")) + mediaTypes.Add("DVD-RW"); + + if(!mediaTypes.Contains("DVD+R")) + mediaTypes.Add("DVD+R"); + + if(!mediaTypes.Contains("DVD+RW")) + mediaTypes.Add("DVD+RW"); + + if(!mediaTypes.Contains("DVD-R DL")) + mediaTypes.Add("DVD-R DL"); + + if(!mediaTypes.Contains("DVD+R DL")) + mediaTypes.Add("DVD+R DL"); + + if(!mediaTypes.Contains("Nintendo GameCube game")) mediaTypes.Add("Nintendo GameCube game"); - if (!mediaTypes.Contains("Nintendo Wii game")) mediaTypes.Add("Nintendo Wii game"); + + if(!mediaTypes.Contains("Nintendo Wii game")) + mediaTypes.Add("Nintendo Wii game"); } - if (report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusMRW) - if (!mediaTypes.Contains("DVD+MRW")) + if(report.SCSI.MultiMediaDevice.Features.CanReadDVDPlusMRW) + if(!mediaTypes.Contains("DVD+MRW")) mediaTypes.Add("DVD+MRW"); - if (report.SCSI.MultiMediaDevice.Features.CanReadHDDVD || - report.SCSI.MultiMediaDevice.Features.CanReadHDDVDR) + if(report.SCSI.MultiMediaDevice.Features.CanReadHDDVD || + report.SCSI.MultiMediaDevice.Features.CanReadHDDVDR) { - if (!mediaTypes.Contains("HD DVD-ROM")) mediaTypes.Add("HD DVD-ROM"); - if (!mediaTypes.Contains("HD DVD-R")) mediaTypes.Add("HD DVD-R"); - if (!mediaTypes.Contains("HD DVD-RW")) mediaTypes.Add("HD DVD-RW"); + if(!mediaTypes.Contains("HD DVD-ROM")) + mediaTypes.Add("HD DVD-ROM"); + + if(!mediaTypes.Contains("HD DVD-R")) + mediaTypes.Add("HD DVD-R"); + + if(!mediaTypes.Contains("HD DVD-RW")) + mediaTypes.Add("HD DVD-RW"); } - if (report.SCSI.MultiMediaDevice.Features.CanReadHDDVDRAM) - if (!mediaTypes.Contains("HD DVD-RAM")) + if(report.SCSI.MultiMediaDevice.Features.CanReadHDDVDRAM) + if(!mediaTypes.Contains("HD DVD-RAM")) mediaTypes.Add("HD DVD-RAM"); } - if (iomegaRev) + if(iomegaRev) { mediaTypes.Add("REV 35Gb"); mediaTypes.Add("REV 70Gb"); @@ -512,18 +624,28 @@ namespace DiscImageChef.Commands // Very old CD drives do not contain mode page 2Ah neither GET CONFIGURATION, so just try all CDs on them // Also don't get confident, some drives didn't know CD-RW but are able to read them - if (mediaTypes.Count == 0 || mediaTypes.Contains("CD-ROM")) + if(mediaTypes.Count == 0 || + mediaTypes.Contains("CD-ROM")) { - if (!mediaTypes.Contains("CD-ROM")) mediaTypes.Add("CD-ROM"); - if (!mediaTypes.Contains("Audio CD")) mediaTypes.Add("Audio CD"); - if (!mediaTypes.Contains("CD-R")) mediaTypes.Add("CD-R"); - if (!mediaTypes.Contains("CD-RW Ultra Speed (marked 16x or higher)")) + if(!mediaTypes.Contains("CD-ROM")) + mediaTypes.Add("CD-ROM"); + + if(!mediaTypes.Contains("Audio CD")) + mediaTypes.Add("Audio CD"); + + if(!mediaTypes.Contains("CD-R")) + mediaTypes.Add("CD-R"); + + if(!mediaTypes.Contains("CD-RW Ultra Speed (marked 16x or higher)")) mediaTypes.Add("CD-RW Ultra Speed (marked 16x or higher)"); - if (!mediaTypes.Contains("CD-RW High Speed (marked between 8x and 12x)")) + + if(!mediaTypes.Contains("CD-RW High Speed (marked between 8x and 12x)")) mediaTypes.Add("CD-RW High Speed (marked between 8x and 12x)"); - if (!mediaTypes.Contains("CD-RW (marked 4x or lower)")) + + if(!mediaTypes.Contains("CD-RW (marked 4x or lower)")) mediaTypes.Add("CD-RW (marked 4x or lower)"); - if (!mediaTypes.Contains("Enhanced CD (aka E-CD, CD-Plus or CD+)")) + + if(!mediaTypes.Contains("Enhanced CD (aka E-CD, CD-Plus or CD+)")) mediaTypes.Add("Enhanced CD (aka E-CD, CD-Plus or CD+)"); } @@ -532,20 +654,23 @@ namespace DiscImageChef.Commands bool tryPlextor = false, tryHldtst = false, tryPioneer = false, tryNec = false; tryPlextor |= dev.Manufacturer.ToLowerInvariant() == "plextor"; - tryHldtst |= dev.Manufacturer.ToLowerInvariant() == "hl-dt-st"; + tryHldtst |= dev.Manufacturer.ToLowerInvariant() == "hl-dt-st"; tryPioneer |= dev.Manufacturer.ToLowerInvariant() == "pioneer"; - tryNec |= dev.Manufacturer.ToLowerInvariant() == "nec"; + tryNec |= dev.Manufacturer.ToLowerInvariant() == "nec"; - if (MainClass.Debug && !iomegaRev) + if(MainClass.Debug && + !iomegaRev) { - if (!tryPlextor) + if(!tryPlextor) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { - DicConsole - .Write( - "Do you have want to try Plextor vendor commands? THIS IS DANGEROUS AND CAN IRREVERSIBLY DESTROY YOUR DRIVE (IF IN DOUBT PRESS 'N') (Y/N): "); + DicConsole. + Write("Do you have want to try Plextor vendor commands? THIS IS DANGEROUS AND CAN IRREVERSIBLY DESTROY YOUR DRIVE (IF IN DOUBT PRESS 'N') (Y/N): "); + pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } @@ -553,14 +678,16 @@ namespace DiscImageChef.Commands tryPlextor |= pressedKey.Key == ConsoleKey.Y; } - if (!tryNec) + if(!tryNec) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { - DicConsole - .Write( - "Do you have want to try NEC vendor commands? THIS IS DANGEROUS AND CAN IRREVERSIBLY DESTROY YOUR DRIVE (IF IN DOUBT PRESS 'N') (Y/N): "); + DicConsole. + Write("Do you have want to try NEC vendor commands? THIS IS DANGEROUS AND CAN IRREVERSIBLY DESTROY YOUR DRIVE (IF IN DOUBT PRESS 'N') (Y/N): "); + pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } @@ -568,14 +695,16 @@ namespace DiscImageChef.Commands tryNec |= pressedKey.Key == ConsoleKey.Y; } - if (!tryPioneer) + if(!tryPioneer) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { - DicConsole - .Write( - "Do you have want to try Pioneer vendor commands? THIS IS DANGEROUS AND CAN IRREVERSIBLY DESTROY YOUR DRIVE (IF IN DOUBT PRESS 'N') (Y/N): "); + DicConsole. + Write("Do you have want to try Pioneer vendor commands? THIS IS DANGEROUS AND CAN IRREVERSIBLY DESTROY YOUR DRIVE (IF IN DOUBT PRESS 'N') (Y/N): "); + pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } @@ -583,14 +712,16 @@ namespace DiscImageChef.Commands tryPioneer |= pressedKey.Key == ConsoleKey.Y; } - if (!tryHldtst) + if(!tryHldtst) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { - DicConsole - .Write( - "Do you have want to try HL-DT-ST (aka LG) vendor commands? THIS IS DANGEROUS AND CAN IRREVERSIBLY DESTROY YOUR DRIVE (IF IN DOUBT PRESS 'N') (Y/N): "); + DicConsole. + Write("Do you have want to try HL-DT-ST (aka LG) vendor commands? THIS IS DANGEROUS AND CAN IRREVERSIBLY DESTROY YOUR DRIVE (IF IN DOUBT PRESS 'N') (Y/N): "); + pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } @@ -599,74 +730,94 @@ namespace DiscImageChef.Commands } } - if (dev.Model.StartsWith("PD-", StringComparison.Ordinal)) mediaTypes.Add("PD-650"); + if(dev.Model.StartsWith("PD-", StringComparison.Ordinal)) + mediaTypes.Add("PD-650"); - var mediaTests = new List(); - foreach (var mediaType in mediaTypes) + List mediaTests = new List(); + + foreach(string mediaType in mediaTypes) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Do you have a {0} disc that you can insert in the drive? (Y/N): ", - mediaType); + mediaType); + pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } - if (pressedKey.Key != ConsoleKey.Y) continue; + if(pressedKey.Key != ConsoleKey.Y) + continue; + + DicConsole. + WriteLine("Please insert it in the drive and press any key when it is ready."); - DicConsole - .WriteLine("Please insert it in the drive and press any key when it is ready."); System.Console.ReadKey(true); - var mediaIsRecognized = true; + bool mediaIsRecognized = true; sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (sense) + + if(sense) { - var decSense = Sense.DecodeFixed(senseBuffer); - if (decSense.HasValue) + FixedSense? decSense = Sense.DecodeFixed(senseBuffer); + + if(decSense.HasValue) { - if (decSense.Value.ASC == 0x3A) + if(decSense.Value.ASC == 0x3A) { - var leftRetries = 50; - while (leftRetries > 0) + int leftRetries = 50; + + while(leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (!sense) break; + + if(!sense) + break; leftRetries--; } mediaIsRecognized &= !sense; } - else if (decSense.Value.ASC == 0x04 && decSense.Value.ASCQ == 0x01) + else if(decSense.Value.ASC == 0x04 && + decSense.Value.ASCQ == 0x01) { - var leftRetries = 50; - while (leftRetries > 0) + int leftRetries = 50; + + while(leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (!sense) break; + + if(!sense) + break; leftRetries--; } mediaIsRecognized &= !sense; } + // These should be trapped by the OS but seems in some cases they're not - else if (decSense.Value.ASC == 0x28) + else if(decSense.Value.ASC == 0x28) { - var leftRetries = 50; - while (leftRetries > 0) + int leftRetries = 50; + + while(leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (!sense) break; + + if(!sense) + break; leftRetries--; } @@ -676,76 +827,90 @@ namespace DiscImageChef.Commands else { DicConsole.DebugWriteLine("Device-Report command", - "Device not ready. Sense {0}h ASC {1:X2}h ASCQ {2:X2}h", - decSense.Value.SenseKey, decSense.Value.ASC, - decSense.Value.ASCQ); + "Device not ready. Sense {0}h ASC {1:X2}h ASCQ {2:X2}h", + decSense.Value.SenseKey, decSense.Value.ASC, + decSense.Value.ASCQ); + mediaIsRecognized = false; } } else { DicConsole.DebugWriteLine("Device-Report command", - "Got sense status but no sense buffer"); + "Got sense status but no sense buffer"); + mediaIsRecognized = false; } } var mediaTest = new TestedMedia(); - if (mediaIsRecognized) + + if(mediaIsRecognized) { mediaTest = reporter.ReportMmcMedia(mediaType, tryPlextor, tryPioneer, tryNec, - tryHldtst); + tryHldtst); - if (mediaTest is null) continue; + if(mediaTest is null) + continue; - if (mediaTest.SupportsReadLong == true && - mediaTest.LongBlockSize == mediaTest.BlockSize) + if(mediaTest.SupportsReadLong == true && + mediaTest.LongBlockSize == mediaTest.BlockSize) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { - DicConsole - .Write( - "Drive supports SCSI READ LONG but I cannot find the correct size. Do you want me to try? (This can take hours) (Y/N): "); + DicConsole. + Write("Drive supports SCSI READ LONG but I cannot find the correct size. Do you want me to try? (This can take hours) (Y/N): "); + pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } - if (pressedKey.Key == ConsoleKey.Y) + if(pressedKey.Key == ConsoleKey.Y) { - for (var i = (ushort) mediaTest.BlockSize;; i++) + for(ushort i = (ushort)mediaTest.BlockSize;; i++) { DicConsole.Write("\rTrying to READ LONG with a size of {0} bytes...", - i); + i); + sense = dev.ReadLong10(out buffer, out senseBuffer, false, false, 0, i, - dev.Timeout, out _); - if (!sense) + dev.Timeout, out _); + + if(!sense) { - if (MainClass.Debug) mediaTest.ReadLong10Data = buffer; + if(MainClass.Debug) + mediaTest.ReadLong10Data = buffer; mediaTest.LongBlockSize = i; + break; } - if (i == ushort.MaxValue) break; + if(i == ushort.MaxValue) + break; } DicConsole.WriteLine(); } } - if (MainClass.Debug && mediaTest.SupportsReadLong == true && - mediaTest.LongBlockSize != mediaTest.BlockSize) + if(MainClass.Debug && + mediaTest.SupportsReadLong == true && + mediaTest.LongBlockSize != mediaTest.BlockSize) { sense = dev.ReadLong10(out buffer, out senseBuffer, false, false, 0, - (ushort) mediaTest.LongBlockSize, dev.Timeout, out _); - if (!sense) mediaTest.ReadLong10Data = buffer; + (ushort)mediaTest.LongBlockSize, dev.Timeout, out _); + + if(!sense) + mediaTest.ReadLong10Data = buffer; } // TODO: READ LONG (16) } - mediaTest.MediumTypeName = mediaType; + mediaTest.MediumTypeName = mediaType; mediaTest.MediaIsRecognized = mediaIsRecognized; mediaTests.Add(mediaTest); @@ -755,28 +920,34 @@ namespace DiscImageChef.Commands report.SCSI.MultiMediaDevice.TestedMedia = mediaTests; } + break; case PeripheralDeviceTypes.SequentialAccess: { report.SCSI.SequentialDevice = reporter.ReportScsiSsc(); - var seqTests = new List(); + List seqTests = new List(); pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.N) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Do you have media that you can insert in the drive? (Y/N): "); pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } - if (pressedKey.Key != ConsoleKey.Y) continue; + if(pressedKey.Key != ConsoleKey.Y) + continue; + + DicConsole. + WriteLine("Please insert it in the drive and press any key when it is ready."); - DicConsole - .WriteLine("Please insert it in the drive and press any key when it is ready."); System.Console.ReadKey(true); DicConsole.Write("Please write a description of the media type and press enter: "); @@ -786,55 +957,68 @@ namespace DiscImageChef.Commands DicConsole.Write("Please write the media model and press enter: "); mediumModel = System.Console.ReadLine(); - var mediaIsRecognized = true; + bool mediaIsRecognized = true; sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); DicConsole.DebugWriteLine("Device reporting", "sense = {0}", sense); - if (sense) + + if(sense) { - var decSense = Sense.DecodeFixed(senseBuffer); - if (decSense.HasValue) + FixedSense? decSense = Sense.DecodeFixed(senseBuffer); + + if(decSense.HasValue) { - if (decSense.Value.ASC == 0x3A) + if(decSense.Value.ASC == 0x3A) { - var leftRetries = 50; - while (leftRetries > 0) + int leftRetries = 50; + + while(leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (!sense) break; + + if(!sense) + break; leftRetries--; } mediaIsRecognized &= !sense; } - else if (decSense.Value.ASC == 0x04 && decSense.Value.ASCQ == 0x01) + else if(decSense.Value.ASC == 0x04 && + decSense.Value.ASCQ == 0x01) { - var leftRetries = 50; - while (leftRetries > 0) + int leftRetries = 50; + + while(leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (!sense) break; + + if(!sense) + break; leftRetries--; } mediaIsRecognized &= !sense; } + // These should be trapped by the OS but seems in some cases they're not - else if (decSense.Value.ASC == 0x28) + else if(decSense.Value.ASC == 0x28) { - var leftRetries = 50; - while (leftRetries > 0) + int leftRetries = 50; + + while(leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (!sense) break; + + if(!sense) + break; leftRetries--; } @@ -844,27 +1028,30 @@ namespace DiscImageChef.Commands else { DicConsole.DebugWriteLine("Device-Report command", - "Device not ready. Sense {0} ASC {1:X2}h ASCQ {2:X2}h", - decSense.Value.SenseKey, decSense.Value.ASC, - decSense.Value.ASCQ); + "Device not ready. Sense {0} ASC {1:X2}h ASCQ {2:X2}h", + decSense.Value.SenseKey, decSense.Value.ASC, + decSense.Value.ASCQ); + mediaIsRecognized = false; } } else { DicConsole.DebugWriteLine("Device-Report command", - "Got sense status but no sense buffer"); + "Got sense status but no sense buffer"); + mediaIsRecognized = false; } } var seqTest = new TestedSequentialMedia(); - if (mediaIsRecognized) seqTest = reporter.ReportSscMedia(); + if(mediaIsRecognized) + seqTest = reporter.ReportSscMedia(); - seqTest.MediumTypeName = mediumTypeName; - seqTest.Manufacturer = mediumManufacturer; - seqTest.Model = mediumModel; + seqTest.MediumTypeName = mediumTypeName; + seqTest.Manufacturer = mediumManufacturer; + seqTest.Model = mediumModel; seqTest.MediaIsRecognized = mediaIsRecognized; seqTests.Add(seqTest); @@ -880,25 +1067,30 @@ namespace DiscImageChef.Commands break; default: { - if (removable) + if(removable) { - var mediaTests = new List(); + List mediaTests = new List(); pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.N) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Do you have media that you can insert in the drive? (Y/N): "); pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } - if (pressedKey.Key != ConsoleKey.Y) continue; + if(pressedKey.Key != ConsoleKey.Y) + continue; + + DicConsole. + WriteLine("Please insert it in the drive and press any key when it is ready."); - DicConsole - .WriteLine("Please insert it in the drive and press any key when it is ready."); System.Console.ReadKey(true); DicConsole.Write("Please write a description of the media type and press enter: "); @@ -908,37 +1100,46 @@ namespace DiscImageChef.Commands DicConsole.Write("Please write the media model and press enter: "); mediumModel = System.Console.ReadLine(); - var mediaIsRecognized = true; + bool mediaIsRecognized = true; sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (sense) + + if(sense) { - var decSense = Sense.DecodeFixed(senseBuffer); - if (decSense.HasValue) - if (decSense.Value.ASC == 0x3A) + FixedSense? decSense = Sense.DecodeFixed(senseBuffer); + + if(decSense.HasValue) + if(decSense.Value.ASC == 0x3A) { - var leftRetries = 20; - while (leftRetries > 0) + int leftRetries = 20; + + while(leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (!sense) break; + + if(!sense) + break; leftRetries--; } mediaIsRecognized &= !sense; } - else if (decSense.Value.ASC == 0x04 && decSense.Value.ASCQ == 0x01) + else if(decSense.Value.ASC == 0x04 && + decSense.Value.ASCQ == 0x01) { - var leftRetries = 20; - while (leftRetries > 0) + int leftRetries = 20; + + while(leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, dev.Timeout, out _); - if (!sense) break; + + if(!sense) + break; leftRetries--; } @@ -949,61 +1150,71 @@ namespace DiscImageChef.Commands { mediaIsRecognized = false; } - else mediaIsRecognized = false; + else + mediaIsRecognized = false; } var mediaTest = new TestedMedia(); - if (mediaIsRecognized) + if(mediaIsRecognized) { mediaTest = reporter.ReportScsiMedia(); - if (mediaTest.SupportsReadLong == true && - mediaTest.LongBlockSize == mediaTest.BlockSize) + if(mediaTest.SupportsReadLong == true && + mediaTest.LongBlockSize == mediaTest.BlockSize) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { - DicConsole - .Write( - "Drive supports SCSI READ LONG but I cannot find the correct size. Do you want me to try? (This can take hours) (Y/N): "); + DicConsole. + Write("Drive supports SCSI READ LONG but I cannot find the correct size. Do you want me to try? (This can take hours) (Y/N): "); + pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } - if (pressedKey.Key == ConsoleKey.Y) + if(pressedKey.Key == ConsoleKey.Y) { - for (var i = (ushort) mediaTest.BlockSize;; i++) + for(ushort i = (ushort)mediaTest.BlockSize;; i++) { - DicConsole - .Write("\rTrying to READ LONG with a size of {0} bytes...", i); + DicConsole. + Write("\rTrying to READ LONG with a size of {0} bytes...", i); + sense = dev.ReadLong10(out buffer, out senseBuffer, false, false, 0, - i, dev.Timeout, out _); - if (!sense) + i, dev.Timeout, out _); + + if(!sense) { mediaTest.LongBlockSize = i; + break; } - if (i == ushort.MaxValue) break; + if(i == ushort.MaxValue) + break; } DicConsole.WriteLine(); } } - if (MainClass.Debug && mediaTest.SupportsReadLong == true && - mediaTest.LongBlockSize != mediaTest.BlockSize) + if(MainClass.Debug && + mediaTest.SupportsReadLong == true && + mediaTest.LongBlockSize != mediaTest.BlockSize) { sense = dev.ReadLong10(out buffer, out senseBuffer, false, false, 0, - (ushort) mediaTest.LongBlockSize, dev.Timeout, out _); - if (!sense) mediaTest.ReadLong10Data = buffer; + (ushort)mediaTest.LongBlockSize, dev.Timeout, out _); + + if(!sense) + mediaTest.ReadLong10Data = buffer; } } - mediaTest.MediumTypeName = mediumTypeName; - mediaTest.Manufacturer = mediumManufacturer; - mediaTest.Model = mediumModel; + mediaTest.MediumTypeName = mediumTypeName; + mediaTest.Manufacturer = mediumManufacturer; + mediaTest.Model = mediumModel; mediaTest.MediaIsRecognized = mediaIsRecognized; mediaTests.Add(mediaTest); @@ -1018,51 +1229,60 @@ namespace DiscImageChef.Commands { report.SCSI.ReadCapabilities = reporter.ReportScsi(); - if (report.SCSI.ReadCapabilities.SupportsReadLong == true && - report.SCSI.ReadCapabilities.LongBlockSize == - report.SCSI.ReadCapabilities.BlockSize) + if(report.SCSI.ReadCapabilities.SupportsReadLong == true && + report.SCSI.ReadCapabilities.LongBlockSize == + report.SCSI.ReadCapabilities.BlockSize) { pressedKey = new ConsoleKeyInfo(); - while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) + + while(pressedKey.Key != ConsoleKey.Y && + pressedKey.Key != ConsoleKey.N) { - DicConsole - .Write( - "Drive supports SCSI READ LONG but I cannot find the correct size. Do you want me to try? (This can take hours) (Y/N): "); + DicConsole. + Write("Drive supports SCSI READ LONG but I cannot find the correct size. Do you want me to try? (This can take hours) (Y/N): "); + pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } - if (pressedKey.Key == ConsoleKey.Y) + if(pressedKey.Key == ConsoleKey.Y) { - for (var i = (ushort) report.SCSI.ReadCapabilities.BlockSize;; i++) + for(ushort i = (ushort)report.SCSI.ReadCapabilities.BlockSize;; i++) { DicConsole.Write("\rTrying to READ LONG with a size of {0} bytes...", i); + sense = dev.ReadLong10(out buffer, out senseBuffer, false, false, 0, i, - dev.Timeout, out _); - if (!sense) + dev.Timeout, out _); + + if(!sense) { - if (MainClass.Debug) + if(MainClass.Debug) report.SCSI.ReadCapabilities.ReadLong10Data = buffer; report.SCSI.ReadCapabilities.LongBlockSize = i; + break; } - if (i == ushort.MaxValue) break; + if(i == ushort.MaxValue) + break; } DicConsole.WriteLine(); } } - if (MainClass.Debug && report.SCSI.ReadCapabilities.SupportsReadLong == true && - report.SCSI.ReadCapabilities.LongBlockSize != - report.SCSI.ReadCapabilities.BlockSize) + if(MainClass.Debug && + report.SCSI.ReadCapabilities.SupportsReadLong == true && + report.SCSI.ReadCapabilities.LongBlockSize != + report.SCSI.ReadCapabilities.BlockSize) { sense = dev.ReadLong10(out buffer, out senseBuffer, false, false, 0, - (ushort) report.SCSI.ReadCapabilities.LongBlockSize, - dev.Timeout, out _); - if (!sense) report.SCSI.ReadCapabilities.ReadLong10Data = buffer; + (ushort)report.SCSI.ReadCapabilities.LongBlockSize, + dev.Timeout, out _); + + if(!sense) + report.SCSI.ReadCapabilities.ReadLong10Data = buffer; } } @@ -1076,23 +1296,26 @@ namespace DiscImageChef.Commands var jsonFs = new FileStream(jsonFile, FileMode.Create); var jsonSw = new StreamWriter(jsonFs); - jsonSw.Write(JsonConvert.SerializeObject(report, Formatting.Indented, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore - })); + + jsonSw.Write(JsonConvert.SerializeObject(report, Formatting.Indented, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + })); + jsonSw.Close(); jsonFs.Close(); - using (var ctx = DicContext.Create(Settings.Settings.LocalDbPath)) + using(var ctx = DicContext.Create(Settings.Settings.LocalDbPath)) { ctx.Reports.Add(new Report(report)); ctx.SaveChanges(); } // TODO: - if (Settings.Settings.Current.ShareReports) Remote.SubmitReport(report); - return (int) ErrorNumber.NoError; + if(Settings.Settings.Current.ShareReports) + Remote.SubmitReport(report); + + return(int)ErrorNumber.NoError; } } } \ No newline at end of file diff --git a/DiscImageChef/Commands/DumpMedia.cs b/DiscImageChef/Commands/DumpMedia.cs index 74bcf3563..3d7a629d8 100644 --- a/DiscImageChef/Commands/DumpMedia.cs +++ b/DiscImageChef/Commands/DumpMedia.cs @@ -36,6 +36,7 @@ using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; +using DiscImageChef.CommonTypes; using DiscImageChef.CommonTypes.Enums; using DiscImageChef.CommonTypes.Interfaces; using DiscImageChef.CommonTypes.Interop; @@ -53,92 +54,107 @@ namespace DiscImageChef.Commands { internal class DumpMediaCommand : Command { - private string cicmXml; - private string devicePath; - private bool doResume = true; - private string encodingName; - private bool firstTrackPregap; - private bool force; - private bool noMetadata; - private bool noTrim; - private string outputFile; - private string outputOptions; + string cicmXml; + string devicePath; + bool doResume = true; + string encodingName; + bool firstTrackPregap; + bool force; + bool noMetadata; + bool noTrim; + string outputFile; + string outputOptions; - private bool persistent; + bool persistent; // TODO: Add raw dumping - private ushort retryPasses = 5; - private bool showHelp; - private int skip = 512; - private bool stopOnError; - private string wantedOutputFormat; + ushort retryPasses = 5; + bool showHelp; + int skip = 512; + bool stopOnError; + string wantedOutputFormat; public DumpMediaCommand() : base("dump-media", "Dumps the media inserted on a device to a media image.") { Options = new OptionSet { $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}", - $"{MainClass.AssemblyCopyright}", - "", - $"usage: DiscImageChef {Name} [OPTIONS] devicepath outputimage", - "", - Help, - {"cicm-xml|x=", "Take metadata from existing CICM XML sidecar.", s => cicmXml = s}, - {"encoding|e=", "Name of character encoding to use.", s => encodingName = s} + $"{MainClass.AssemblyCopyright}", "", $"usage: DiscImageChef {Name} [OPTIONS] devicepath outputimage", + "", Help, + { + "cicm-xml|x=", "Take metadata from existing CICM XML sidecar.", s => cicmXml = s + }, + { + "encoding|e=", "Name of character encoding to use.", s => encodingName = s + } }; - if (DetectOS.GetRealPlatformID() != PlatformID.FreeBSD) + if(DetectOS.GetRealPlatformID() != PlatformID.FreeBSD) Options.Add("first-pregap", "Try to read first track pregap. Only applicable to CD/DDCD/GD.", - b => firstTrackPregap = b != null); + b => firstTrackPregap = b != null); Options.Add("force|f", "Continue dump whatever happens.", b => force = b != null); + Options.Add("format|t=", - "Format of the output image, as plugin name or plugin id. If not present, will try to detect it from output image extension.", - s => wantedOutputFormat = s); - Options.Add("no-metadata", "Disables creating CICM XML sidecar.", b => noMetadata = b != null); + "Format of the output image, as plugin name or plugin id. If not present, will try to detect it from output image extension.", + s => wantedOutputFormat = s); + + Options.Add("no-metadata", "Disables creating CICM XML sidecar.", b => noMetadata = b != null); Options.Add("no-trim", "Disables trimming errored from skipped sectors.", b => noTrim = b != null); + Options.Add("options|O=", "Comma separated name=value pairs of options to pass to output image plugin.", - s => outputOptions = s); + s => outputOptions = s); + Options.Add("persistent", "Try to recover partial or incorrect data.", b => persistent = b != null); + /* TODO: Disabled temporarily Options.Add("raw|r", "Dump sectors with tags included. For optical media, dump scrambled sectors.", (b) => raw = b != null);*/ Options.Add("resume|r", "Create/use resume mapfile.", - b => doResume = b != null); - Options.Add("retry-passes|p=", "How many retry passes to do.", - (ushort us) => retryPasses = us); - Options.Add("skip|k=", "When an unreadable sector is found skip this many sectors.", - (int i) => skip = i); + b => doResume = b != null); + + Options.Add("retry-passes|p=", "How many retry passes to do.", (ushort us) => retryPasses = us); + Options.Add("skip|k=", "When an unreadable sector is found skip this many sectors.", (int i) => skip = i); + Options.Add("stop-on-error|s", "Stop media dump on first error.", - b => stopOnError = b != null); + b => stopOnError = b != null); + Options.Add("help|h|?", "Show this message and exit.", - v => showHelp = v != null); + v => showHelp = v != null); } public override int Invoke(IEnumerable arguments) { - var extra = Options.Parse(arguments); + List extra = Options.Parse(arguments); - if (showHelp) + if(showHelp) { Options.WriteOptionDescriptions(CommandSet.Out); - return (int) ErrorNumber.HelpRequested; + + return(int)ErrorNumber.HelpRequested; } MainClass.PrintCopyright(); - if (MainClass.Debug) DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; - if (MainClass.Verbose) DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + + if(MainClass.Debug) + DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; + + if(MainClass.Verbose) + DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + Statistics.AddCommand("dump-media"); - if (extra.Count > 2) + if(extra.Count > 2) { DicConsole.ErrorWriteLine("Too many arguments."); - return (int) ErrorNumber.UnexpectedArgumentCount; + + return(int)ErrorNumber.UnexpectedArgumentCount; } - if (extra.Count <= 1) + if(extra.Count <= 1) { DicConsole.ErrorWriteLine("Missing paths."); - return (int) ErrorNumber.MissingArgument; + + return(int)ErrorNumber.MissingArgument; } devicePath = extra[0]; @@ -156,6 +172,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Dump-Media command", "--options={0}", Options); DicConsole.DebugWriteLine("Dump-Media command", "--output={0}", outputFile); DicConsole.DebugWriteLine("Dump-Media command", "--persistent={0}", persistent); + // TODO: Disabled temporarily //DicConsole.DebugWriteLine("Dump-Media command", "--raw={0}", raw); DicConsole.DebugWriteLine("Dump-Media command", "--resume={0}", doResume); @@ -164,129 +181,155 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Dump-Media command", "--stop-on-error={0}", stopOnError); DicConsole.DebugWriteLine("Dump-Media command", "--verbose={0}", MainClass.Verbose); - var parsedOptions = Core.Options.Parse(outputOptions); + Dictionary parsedOptions = Core.Options.Parse(outputOptions); DicConsole.DebugWriteLine("Dump-Media command", "Parsed options:"); - foreach (var parsedOption in parsedOptions) + + foreach(KeyValuePair parsedOption in parsedOptions) DicConsole.DebugWriteLine("Dump-Media command", "{0} = {1}", parsedOption.Key, parsedOption.Value); Encoding encoding = null; - if (encodingName != null) + if(encodingName != null) try { encoding = Claunia.Encoding.Encoding.GetEncoding(encodingName); - if (MainClass.Verbose) + + if(MainClass.Verbose) DicConsole.VerboseWriteLine("Using encoding for {0}.", encoding.EncodingName); } - catch (ArgumentException) + catch(ArgumentException) { DicConsole.ErrorWriteLine("Specified encoding is not supported."); - return (int) ErrorNumber.EncodingUnknown; + + return(int)ErrorNumber.EncodingUnknown; } - if (devicePath.Length == 2 && devicePath[1] == ':' && devicePath[0] != '/' && char.IsLetter(devicePath[0])) + if(devicePath.Length == 2 && + devicePath[1] == ':' && + devicePath[0] != '/' && + char.IsLetter(devicePath[0])) devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':'; Device dev; + try { dev = new Device(devicePath); - if (dev.Error) + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); + + if(dev.Error) { DicConsole.ErrorWriteLine(Error.Print(dev.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } } - catch (DeviceException e) + catch(DeviceException e) { DicConsole.ErrorWriteLine(e.Message ?? Error.Print(e.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } Statistics.AddDevice(dev); - var outputPrefix = Path.Combine(Path.GetDirectoryName(outputFile), - Path.GetFileNameWithoutExtension(outputFile)); + string outputPrefix = Path.Combine(Path.GetDirectoryName(outputFile), + Path.GetFileNameWithoutExtension(outputFile)); Resume resume = null; - var xs = new XmlSerializer(typeof(Resume)); - if (File.Exists(outputPrefix + ".resume.xml") && doResume) + var xs = new XmlSerializer(typeof(Resume)); + + if(File.Exists(outputPrefix + ".resume.xml") && doResume) try { var sr = new StreamReader(outputPrefix + ".resume.xml"); - resume = (Resume) xs.Deserialize(sr); + resume = (Resume)xs.Deserialize(sr); sr.Close(); } catch { DicConsole.ErrorWriteLine("Incorrect resume file, not continuing..."); - return (int) ErrorNumber.InvalidResume; + + return(int)ErrorNumber.InvalidResume; } - if (resume != null && resume.NextBlock > resume.LastBlock && resume.BadBlocks.Count == 0 && !resume.Tape) + if(resume != null && + resume.NextBlock > resume.LastBlock && + resume.BadBlocks.Count == 0 && + !resume.Tape) { DicConsole.WriteLine("Media already dumped correctly, not continuing..."); - return (int) ErrorNumber.AlreadyDumped; + + return(int)ErrorNumber.AlreadyDumped; } - CICMMetadataType sidecar = null; - var sidecarXs = new XmlSerializer(typeof(CICMMetadataType)); - if (cicmXml != null) - if (File.Exists(cicmXml)) + CICMMetadataType sidecar = null; + var sidecarXs = new XmlSerializer(typeof(CICMMetadataType)); + + if(cicmXml != null) + if(File.Exists(cicmXml)) { try { var sr = new StreamReader(cicmXml); - sidecar = (CICMMetadataType) sidecarXs.Deserialize(sr); + sidecar = (CICMMetadataType)sidecarXs.Deserialize(sr); sr.Close(); } catch { DicConsole.ErrorWriteLine("Incorrect metadata sidecar file, not continuing..."); - return (int) ErrorNumber.InvalidSidecar; + + return(int)ErrorNumber.InvalidSidecar; } } else { DicConsole.ErrorWriteLine("Could not find metadata sidecar, not continuing..."); - return (int) ErrorNumber.FileNotFound; + + return(int)ErrorNumber.FileNotFound; } - var plugins = GetPluginBase.Instance; - var candidates = new List(); + PluginBase plugins = GetPluginBase.Instance; + List candidates = new List(); // Try extension - if (string.IsNullOrEmpty(wantedOutputFormat)) + if(string.IsNullOrEmpty(wantedOutputFormat)) candidates.AddRange(plugins.WritableImages.Values.Where(t => - t.KnownExtensions - .Contains(Path.GetExtension(outputFile)))); + t.KnownExtensions. + Contains(Path.GetExtension(outputFile)))); + // Try Id - else if (Guid.TryParse(wantedOutputFormat, out var outId)) + else if(Guid.TryParse(wantedOutputFormat, out Guid outId)) candidates.AddRange(plugins.WritableImages.Values.Where(t => t.Id.Equals(outId))); + // Try name else candidates.AddRange(plugins.WritableImages.Values.Where(t => string.Equals(t.Name, wantedOutputFormat, - StringComparison - .InvariantCultureIgnoreCase))); + StringComparison. + InvariantCultureIgnoreCase))); - if (candidates.Count == 0) + if(candidates.Count == 0) { DicConsole.WriteLine("No plugin supports requested extension."); - return (int) ErrorNumber.FormatNotFound; + + return(int)ErrorNumber.FormatNotFound; } - if (candidates.Count > 1) + if(candidates.Count > 1) { DicConsole.WriteLine("More than one plugin supports requested extension."); - return (int) ErrorNumber.TooManyFormats; + + return(int)ErrorNumber.TooManyFormats; } - var outputFormat = candidates[0]; + IWritableImage outputFormat = candidates[0]; var dumpLog = new DumpLog(outputPrefix + ".log", dev); - if (MainClass.Verbose) + if(MainClass.Verbose) { dumpLog.WriteLine("Output image format: {0} ({1}).", outputFormat.Name, outputFormat.Id); DicConsole.VerboseWriteLine("Output image format: {0} ({1}).", outputFormat.Name, outputFormat.Id); @@ -298,18 +341,20 @@ namespace DiscImageChef.Commands } var dumper = new Dump(doResume, dev, devicePath, outputFormat, retryPasses, force, false, persistent, - stopOnError, resume, dumpLog, encoding, outputPrefix, outputFile, parsedOptions, - sidecar, (uint) skip, noMetadata, noTrim, firstTrackPregap); - dumper.UpdateStatus += Progress.UpdateStatus; - dumper.ErrorMessage += Progress.ErrorMessage; + stopOnError, resume, dumpLog, encoding, outputPrefix, outputFile, parsedOptions, + sidecar, (uint)skip, noMetadata, noTrim, firstTrackPregap); + + dumper.UpdateStatus += Progress.UpdateStatus; + dumper.ErrorMessage += Progress.ErrorMessage; dumper.StoppingErrorMessage += Progress.ErrorMessage; - dumper.UpdateProgress += Progress.UpdateProgress; - dumper.PulseProgress += Progress.PulseProgress; - dumper.InitProgress += Progress.InitProgress; - dumper.EndProgress += Progress.EndProgress; - dumper.InitProgress2 += Progress.InitProgress2; - dumper.EndProgress2 += Progress.EndProgress2; - dumper.UpdateProgress2 += Progress.UpdateProgress2; + dumper.UpdateProgress += Progress.UpdateProgress; + dumper.PulseProgress += Progress.PulseProgress; + dumper.InitProgress += Progress.InitProgress; + dumper.EndProgress += Progress.EndProgress; + dumper.InitProgress2 += Progress.InitProgress2; + dumper.EndProgress2 += Progress.EndProgress2; + dumper.UpdateProgress2 += Progress.UpdateProgress2; + System.Console.CancelKeyPress += (sender, e) => { e.Cancel = true; @@ -319,7 +364,8 @@ namespace DiscImageChef.Commands dumper.Start(); dev.Close(); - return (int) ErrorNumber.NoError; + + return(int)ErrorNumber.NoError; } } } \ No newline at end of file diff --git a/DiscImageChef/Commands/ListDevices.cs b/DiscImageChef/Commands/ListDevices.cs index 1ef46eec1..f615029fe 100644 --- a/DiscImageChef/Commands/ListDevices.cs +++ b/DiscImageChef/Commands/ListDevices.cs @@ -42,53 +42,67 @@ namespace DiscImageChef.Commands { internal class ListDevicesCommand : Command { - private bool showHelp; + bool showHelp; - public ListDevicesCommand() : base("list-devices", "Lists all connected devices.") + public ListDevicesCommand() : base("list-devices", "Lists all connected devices.") => Options = new OptionSet { - Options = new OptionSet + $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}", + $"{MainClass.AssemblyCopyright}", "", $"usage: DiscImageChef {Name} [dic-remote-host]", "", + Help, { - $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}", - $"{MainClass.AssemblyCopyright}", - "", - $"usage: DiscImageChef {Name} [dic-remote-host]", - "", - Help, - {"help|h|?", "Show this message and exit.", v => showHelp = v != null} - }; - } + "help|h|?", "Show this message and exit.", v => showHelp = v != null + } + }; public override int Invoke(IEnumerable arguments) { - var extra = Options.Parse(arguments); + List extra = Options.Parse(arguments); - if (showHelp) + if(showHelp) { Options.WriteOptionDescriptions(CommandSet.Out); - return (int) ErrorNumber.HelpRequested; + + return(int)ErrorNumber.HelpRequested; } MainClass.PrintCopyright(); - if (MainClass.Debug) DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; - if (MainClass.Verbose) DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + + if(MainClass.Debug) + DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; + + if(MainClass.Verbose) + DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + Statistics.AddCommand("list-devices"); string dicRemote = null; - if (extra.Count > 1) + if(extra.Count > 1) { DicConsole.ErrorWriteLine("Too many arguments."); - return (int) ErrorNumber.UnexpectedArgumentCount; + + return(int)ErrorNumber.UnexpectedArgumentCount; } - if (extra.Count == 1) dicRemote = extra[0]; + if(extra.Count == 1) + dicRemote = extra[0]; DicConsole.DebugWriteLine("List-Devices command", "--debug={0}", MainClass.Debug); DicConsole.DebugWriteLine("List-Devices command", "--verbose={0}", MainClass.Verbose); - var devices = Device.ListDevices(dicRemote); + DeviceInfo[] devices = Device.ListDevices(out bool isRemote, out string serverApplication, + out string serverVersion, out string serverOperatingSystem, + out string serverOperatingSystemVersion, + out string serverArchitecture, dicRemote); - if (devices == null || devices.Length == 0) + if(isRemote) + { + Statistics.AddRemote(serverApplication, serverVersion, serverOperatingSystem, + serverOperatingSystemVersion, serverArchitecture); + } + + if(devices == null || + devices.Length == 0) { DicConsole.WriteLine("No known devices attached."); } @@ -96,32 +110,36 @@ namespace DiscImageChef.Commands { devices = devices.OrderBy(d => d.Path).ToArray(); - if (dicRemote is null) + if(dicRemote is null) { DicConsole.WriteLine("{0,-22}|{1,-16}|{2,-24}|{3,-24}|{4,-10}|{5,-10}", "Path", "Vendor", "Model", - "Serial", "Bus", "Supported?"); + "Serial", "Bus", "Supported?"); + DicConsole.WriteLine("{0,-22}+{1,-16}+{2,-24}+{3,-24}+{4,-10}+{5,-10}", "----------------------", - "----------------", "------------------------", "------------------------", - "----------", "----------"); - foreach (var dev in devices) + "----------------", "------------------------", "------------------------", + "----------", "----------"); + + foreach(DeviceInfo dev in devices) DicConsole.WriteLine("{0,-22}|{1,-16}|{2,-24}|{3,-24}|{4,-10}|{5,-10}", dev.Path, dev.Vendor, - dev.Model, dev.Serial, dev.Bus, dev.Supported); + dev.Model, dev.Serial, dev.Bus, dev.Supported); } else { DicConsole.WriteLine("{0,-48}|{1,-16}|{2,-24}|{3,-24}|{4,-10}|{5,-10}", "Path", "Vendor", "Model", - "Serial", "Bus", "Supported?"); + "Serial", "Bus", "Supported?"); + DicConsole.WriteLine("{0,-48}+{1,-16}+{2,-24}+{3,-24}+{4,-10}+{5,-10}", - "------------------------------------------------", - "----------------", "------------------------", "------------------------", - "----------", "----------"); - foreach (var dev in devices) + "------------------------------------------------", "----------------", + "------------------------", "------------------------", "----------", + "----------"); + + foreach(DeviceInfo dev in devices) DicConsole.WriteLine("{0,-48}|{1,-16}|{2,-24}|{3,-24}|{4,-10}|{5,-10}", dev.Path, dev.Vendor, - dev.Model, dev.Serial, dev.Bus, dev.Supported); + dev.Model, dev.Serial, dev.Bus, dev.Supported); } } - return (int) ErrorNumber.NoError; + return(int)ErrorNumber.NoError; } } } \ No newline at end of file diff --git a/DiscImageChef/Commands/MediaInfo.cs b/DiscImageChef/Commands/MediaInfo.cs index 6e1f846bf..96314bd27 100644 --- a/DiscImageChef/Commands/MediaInfo.cs +++ b/DiscImageChef/Commands/MediaInfo.cs @@ -55,53 +55,57 @@ namespace DiscImageChef.Commands { internal class MediaInfoCommand : Command { - private string devicePath; - private string outputPrefix; - private bool showHelp; + string devicePath; + string outputPrefix; + bool showHelp; - public MediaInfoCommand() : base("media-info", "Gets information about the media inserted on a device.") - { + public MediaInfoCommand() : base("media-info", "Gets information about the media inserted on a device.") => Options = new OptionSet { $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}", - $"{MainClass.AssemblyCopyright}", - "", - $"usage: DiscImageChef {Name} [OPTIONS] devicepath", - "", + $"{MainClass.AssemblyCopyright}", "", $"usage: DiscImageChef {Name} [OPTIONS] devicepath", "", Help, - {"output-prefix|w=", "Write binary responses from device with that prefix.", s => outputPrefix = s}, { - "help|h|?", "Show this message and exit.", - v => showHelp = v != null + "output-prefix|w=", "Write binary responses from device with that prefix.", s => outputPrefix = s + }, + { + "help|h|?", "Show this message and exit.", v => showHelp = v != null } }; - } public override int Invoke(IEnumerable arguments) { - var extra = Options.Parse(arguments); + List extra = Options.Parse(arguments); - if (showHelp) + if(showHelp) { Options.WriteOptionDescriptions(CommandSet.Out); - return (int) ErrorNumber.HelpRequested; + + return(int)ErrorNumber.HelpRequested; } MainClass.PrintCopyright(); - if (MainClass.Debug) DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; - if (MainClass.Verbose) DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + + if(MainClass.Debug) + DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; + + if(MainClass.Verbose) + DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + Statistics.AddCommand("media-info"); - if (extra.Count > 1) + if(extra.Count > 1) { DicConsole.ErrorWriteLine("Too many arguments."); - return (int) ErrorNumber.UnexpectedArgumentCount; + + return(int)ErrorNumber.UnexpectedArgumentCount; } - if (extra.Count == 0) + if(extra.Count == 0) { DicConsole.ErrorWriteLine("Missing device path."); - return (int) ErrorNumber.MissingArgument; + + return(int)ErrorNumber.MissingArgument; } devicePath = extra[0]; @@ -111,79 +115,87 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "--output-prefix={0}", outputPrefix); DicConsole.DebugWriteLine("Media-Info command", "--verbose={0}", MainClass.Verbose); - if (devicePath.Length == 2 && devicePath[1] == ':' && devicePath[0] != '/' && char.IsLetter(devicePath[0])) + if(devicePath.Length == 2 && + devicePath[1] == ':' && + devicePath[0] != '/' && + char.IsLetter(devicePath[0])) devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':'; Device dev; + try { dev = new Device(devicePath); - if (dev.Error) + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); + + if(dev.Error) { DicConsole.ErrorWriteLine(Error.Print(dev.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } } - catch (DeviceException e) + catch(DeviceException e) { DicConsole.ErrorWriteLine(e.Message ?? Error.Print(e.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } Statistics.AddDevice(dev); - switch (dev.Type) + switch(dev.Type) { case DeviceType.ATA: DoAtaMediaInfo(); + break; case DeviceType.MMC: case DeviceType.SecureDigital: DoSdMediaInfo(); + break; case DeviceType.NVMe: DoNvmeMediaInfo(outputPrefix, dev); + break; case DeviceType.ATAPI: case DeviceType.SCSI: DoScsiMediaInfo(outputPrefix, dev); + break; default: throw new NotSupportedException("Unknown device type."); } - return (int) ErrorNumber.NoError; + return(int)ErrorNumber.NoError; } - private static void DoAtaMediaInfo() - { - DicConsole.ErrorWriteLine("Please use device-info command for ATA devices."); - } + static void DoAtaMediaInfo() => DicConsole.ErrorWriteLine("Please use device-info command for ATA devices."); - private static void DoNvmeMediaInfo(string outputPrefix, Device dev) - { + static void DoNvmeMediaInfo(string outputPrefix, Device dev) => throw new NotImplementedException("NVMe devices not yet supported."); - } - private static void DoSdMediaInfo() - { - DicConsole.ErrorWriteLine("Please use device-info command for MMC/SD devices."); - } + static void DoSdMediaInfo() => DicConsole.ErrorWriteLine("Please use device-info command for MMC/SD devices."); - private static void DoScsiMediaInfo(string outputPrefix, Device dev) + static void DoScsiMediaInfo(string outputPrefix, Device dev) { var scsiInfo = new ScsiInfo(dev); - if (!scsiInfo.MediaInserted) return; + if(!scsiInfo.MediaInserted) + return; - if (scsiInfo.DeviceInfo.ScsiModeSense6 != null) + if(scsiInfo.DeviceInfo.ScsiModeSense6 != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_scsi_modesense6.bin", "SCSI MODE SENSE (6)", - scsiInfo.DeviceInfo.ScsiModeSense6); - if (scsiInfo.DeviceInfo.ScsiModeSense10 != null) - DataFile.WriteTo("Media-Info command", outputPrefix, "_scsi_modesense10.bin", "SCSI MODE SENSE (10)", - scsiInfo.DeviceInfo.ScsiModeSense10); + scsiInfo.DeviceInfo.ScsiModeSense6); - switch (dev.ScsiType) + if(scsiInfo.DeviceInfo.ScsiModeSense10 != null) + DataFile.WriteTo("Media-Info command", outputPrefix, "_scsi_modesense10.bin", "SCSI MODE SENSE (10)", + scsiInfo.DeviceInfo.ScsiModeSense10); + + switch(dev.ScsiType) { case PeripheralDeviceTypes.DirectAccess: case PeripheralDeviceTypes.MultiMediaDevice: @@ -191,37 +203,40 @@ namespace DiscImageChef.Commands case PeripheralDeviceTypes.OpticalDevice: case PeripheralDeviceTypes.SimplifiedDevice: case PeripheralDeviceTypes.WriteOnceDevice: - if (scsiInfo.ReadCapacity != null) + if(scsiInfo.ReadCapacity != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readcapacity.bin", "SCSI READ CAPACITY", - scsiInfo.ReadCapacity); + scsiInfo.ReadCapacity); - if (scsiInfo.ReadCapacity16 != null) + if(scsiInfo.ReadCapacity16 != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readcapacity16.bin", - "SCSI READ CAPACITY(16)", scsiInfo.ReadCapacity16); + "SCSI READ CAPACITY(16)", scsiInfo.ReadCapacity16); - if (scsiInfo.Blocks != 0 && scsiInfo.BlockSize != 0) + if(scsiInfo.Blocks != 0 && + scsiInfo.BlockSize != 0) DicConsole.WriteLine("Media has {0} blocks of {1} bytes/each. (for a total of {2} bytes)", - scsiInfo.Blocks, scsiInfo.BlockSize, scsiInfo.Blocks * scsiInfo.BlockSize); + scsiInfo.Blocks, scsiInfo.BlockSize, scsiInfo.Blocks * scsiInfo.BlockSize); break; case PeripheralDeviceTypes.SequentialAccess: - if (scsiInfo.DensitySupport != null) + if(scsiInfo.DensitySupport != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_ssc_reportdensitysupport_media.bin", - "SSC REPORT DENSITY SUPPORT (MEDIA)", scsiInfo.DensitySupport); - if (scsiInfo.DensitySupportHeader.HasValue) + "SSC REPORT DENSITY SUPPORT (MEDIA)", scsiInfo.DensitySupport); + + if(scsiInfo.DensitySupportHeader.HasValue) { DicConsole.WriteLine("Densities supported by currently inserted media:"); DicConsole.WriteLine(DensitySupport.PrettifyDensity(scsiInfo.DensitySupportHeader)); } } - if (scsiInfo.MediaTypeSupport != null) + if(scsiInfo.MediaTypeSupport != null) { DataFile.WriteTo("Media-Info command", outputPrefix, - "_ssc_reportdensitysupport_medium_media.bin", - "SSC REPORT DENSITY SUPPORT (MEDIUM & MEDIA)", scsiInfo.MediaTypeSupport); - if (scsiInfo.MediaTypeSupportHeader.HasValue) + "_ssc_reportdensitysupport_medium_media.bin", + "SSC REPORT DENSITY SUPPORT (MEDIUM & MEDIA)", scsiInfo.MediaTypeSupport); + + if(scsiInfo.MediaTypeSupportHeader.HasValue) { DicConsole.WriteLine("Medium types currently inserted in device:"); DicConsole.WriteLine(DensitySupport.PrettifyMediumType(scsiInfo.MediaTypeSupportHeader)); @@ -233,258 +248,285 @@ namespace DiscImageChef.Commands break; } - if (dev.ScsiType == PeripheralDeviceTypes.MultiMediaDevice) + if(dev.ScsiType == PeripheralDeviceTypes.MultiMediaDevice) { - if (scsiInfo.MmcConfiguration != null) + if(scsiInfo.MmcConfiguration != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_getconfiguration_current.bin", - "SCSI GET CONFIGURATION", scsiInfo.MmcConfiguration); + "SCSI GET CONFIGURATION", scsiInfo.MmcConfiguration); - if (scsiInfo.RecognizedFormatLayers != null) + if(scsiInfo.RecognizedFormatLayers != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_formatlayers.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.RecognizedFormatLayers); + "SCSI READ DISC STRUCTURE", scsiInfo.RecognizedFormatLayers); - if (scsiInfo.WriteProtectionStatus != null) + if(scsiInfo.WriteProtectionStatus != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_writeprotection.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.WriteProtectionStatus); + "SCSI READ DISC STRUCTURE", scsiInfo.WriteProtectionStatus); - if (scsiInfo.DvdPfi != null) + if(scsiInfo.DvdPfi != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_pfi.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdPfi); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdPfi); - if (scsiInfo.DecodedPfi.HasValue) + if(scsiInfo.DecodedPfi.HasValue) DicConsole.WriteLine("PFI:\n{0}", PFI.Prettify(scsiInfo.DecodedPfi)); } - if (scsiInfo.DvdDmi != null) + if(scsiInfo.DvdDmi != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_dmi.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdDmi); - if (DMI.IsXbox(scsiInfo.DvdDmi)) + "SCSI READ DISC STRUCTURE", scsiInfo.DvdDmi); + + if(DMI.IsXbox(scsiInfo.DvdDmi)) DicConsole.WriteLine("Xbox DMI:\n{0}", DMI.PrettifyXbox(scsiInfo.DvdDmi)); - else if (DMI.IsXbox360(scsiInfo.DvdDmi)) + else if(DMI.IsXbox360(scsiInfo.DvdDmi)) DicConsole.WriteLine("Xbox 360 DMI:\n{0}", DMI.PrettifyXbox360(scsiInfo.DvdDmi)); } - if (scsiInfo.DvdCmi != null) + if(scsiInfo.DvdCmi != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_cmi.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdCmi); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdCmi); + DicConsole.WriteLine("Lead-In CMI:\n{0}", CSS_CPRM.PrettifyLeadInCopyright(scsiInfo.DvdCmi)); } - if (scsiInfo.DvdBca != null) + if(scsiInfo.DvdBca != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_bca.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdBca); - if (scsiInfo.DvdAacs != null) + "SCSI READ DISC STRUCTURE", scsiInfo.DvdBca); + + if(scsiInfo.DvdAacs != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_aacs.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdAacs); - if (scsiInfo.DvdRamDds != null) + "SCSI READ DISC STRUCTURE", scsiInfo.DvdAacs); + + if(scsiInfo.DvdRamDds != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_dds.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamDds); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamDds); + DicConsole.WriteLine("Disc Definition Structure:\n{0}", DDS.Prettify(scsiInfo.DvdRamDds)); } - if (scsiInfo.DvdRamCartridgeStatus != null) + if(scsiInfo.DvdRamCartridgeStatus != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_status.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamCartridgeStatus); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamCartridgeStatus); + DicConsole.WriteLine("Medium Status:\n{0}", Cartridge.Prettify(scsiInfo.DvdRamCartridgeStatus)); } - if (scsiInfo.DvdRamSpareArea != null) + if(scsiInfo.DvdRamSpareArea != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_spare.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamSpareArea); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamSpareArea); + DicConsole.WriteLine("Spare Area Information:\n{0}", Spare.Prettify(scsiInfo.DvdRamSpareArea)); } - if (scsiInfo.LastBorderOutRmd != null) + if(scsiInfo.LastBorderOutRmd != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_lastrmd.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.LastBorderOutRmd); + "SCSI READ DISC STRUCTURE", scsiInfo.LastBorderOutRmd); - if (scsiInfo.DvdPreRecordedInfo != null) + if(scsiInfo.DvdPreRecordedInfo != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_pri.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdPreRecordedInfo); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdPreRecordedInfo); - if (scsiInfo.DvdrMediaIdentifier != null) + if(scsiInfo.DvdrMediaIdentifier != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_mediaid.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdrMediaIdentifier); - if (scsiInfo.DvdrPhysicalInformation != null) + "SCSI READ DISC STRUCTURE", scsiInfo.DvdrMediaIdentifier); + + if(scsiInfo.DvdrPhysicalInformation != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_pfi.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdrPhysicalInformation); - if (scsiInfo.DvdPlusAdip != null) + "SCSI READ DISC STRUCTURE", scsiInfo.DvdrPhysicalInformation); + + if(scsiInfo.DvdPlusAdip != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd+_adip.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdPlusAdip); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdPlusAdip); - if (scsiInfo.DvdPlusDcb != null) + if(scsiInfo.DvdPlusDcb != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd+_dcb.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdPlusDcb); - if (scsiInfo.HddvdCopyrightInformation != null) + "SCSI READ DISC STRUCTURE", scsiInfo.DvdPlusDcb); + + if(scsiInfo.HddvdCopyrightInformation != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvd_cmi.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.HddvdCopyrightInformation); - if (scsiInfo.HddvdrMediumStatus != null) + "SCSI READ DISC STRUCTURE", scsiInfo.HddvdCopyrightInformation); + + if(scsiInfo.HddvdrMediumStatus != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvdr_status.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.HddvdrMediumStatus); + "SCSI READ DISC STRUCTURE", scsiInfo.HddvdrMediumStatus); - if (scsiInfo.HddvdrLastRmd != null) + if(scsiInfo.HddvdrLastRmd != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvdr_lastrmd.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.HddvdrLastRmd); + "SCSI READ DISC STRUCTURE", scsiInfo.HddvdrLastRmd); - if (scsiInfo.DvdrLayerCapacity != null) + if(scsiInfo.DvdrLayerCapacity != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_layercap.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdrLayerCapacity); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdrLayerCapacity); - if (scsiInfo.DvdrDlMiddleZoneStart != null) + if(scsiInfo.DvdrDlMiddleZoneStart != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_mzs.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlMiddleZoneStart); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlMiddleZoneStart); - if (scsiInfo.DvdrDlJumpIntervalSize != null) + if(scsiInfo.DvdrDlJumpIntervalSize != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_jis.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlJumpIntervalSize); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlJumpIntervalSize); - if (scsiInfo.DvdrDlManualLayerJumpStartLba != null) + if(scsiInfo.DvdrDlManualLayerJumpStartLba != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_manuallj.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlManualLayerJumpStartLba); + "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlManualLayerJumpStartLba); - if (scsiInfo.DvdrDlRemapAnchorPoint != null) + if(scsiInfo.DvdrDlRemapAnchorPoint != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_remapanchor.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlRemapAnchorPoint); - if (scsiInfo.BlurayDiscInformation != null) + "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlRemapAnchorPoint); + + if(scsiInfo.BlurayDiscInformation != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_di.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.BlurayDiscInformation); + "SCSI READ DISC STRUCTURE", scsiInfo.BlurayDiscInformation); + DicConsole.WriteLine("Blu-ray Disc Information:\n{0}", DI.Prettify(scsiInfo.BlurayDiscInformation)); } - if (scsiInfo.BlurayPac != null) + if(scsiInfo.BlurayPac != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_pac.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.BlurayPac); + "SCSI READ DISC STRUCTURE", scsiInfo.BlurayPac); - if (scsiInfo.BlurayBurstCuttingArea != null) + if(scsiInfo.BlurayBurstCuttingArea != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_bca.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.BlurayBurstCuttingArea); + "SCSI READ DISC STRUCTURE", scsiInfo.BlurayBurstCuttingArea); + DicConsole.WriteLine("Blu-ray Burst Cutting Area:\n{0}", - BCA.Prettify(scsiInfo.BlurayBurstCuttingArea)); + BCA.Prettify(scsiInfo.BlurayBurstCuttingArea)); } - if (scsiInfo.BlurayDds != null) + if(scsiInfo.BlurayDds != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_dds.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.BlurayDds); + "SCSI READ DISC STRUCTURE", scsiInfo.BlurayDds); + DicConsole.WriteLine("Blu-ray Disc Definition Structure:\n{0}", - Decoders.Bluray.DDS.Prettify(scsiInfo.BlurayDds)); + Decoders.Bluray.DDS.Prettify(scsiInfo.BlurayDds)); } - if (scsiInfo.BlurayCartridgeStatus != null) + if(scsiInfo.BlurayCartridgeStatus != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_cartstatus.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.BlurayCartridgeStatus); + "SCSI READ DISC STRUCTURE", scsiInfo.BlurayCartridgeStatus); + DicConsole.WriteLine("Blu-ray Cartridge Status:\n{0}", - Decoders.Bluray.Cartridge.Prettify(scsiInfo.BlurayCartridgeStatus)); + Decoders.Bluray.Cartridge.Prettify(scsiInfo.BlurayCartridgeStatus)); } - if (scsiInfo.BluraySpareAreaInformation != null) + if(scsiInfo.BluraySpareAreaInformation != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_spare.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.BluraySpareAreaInformation); + "SCSI READ DISC STRUCTURE", scsiInfo.BluraySpareAreaInformation); + DicConsole.WriteLine("Blu-ray Spare Area Information:\n{0}", - Decoders.Bluray.Spare.Prettify(scsiInfo.BluraySpareAreaInformation)); + Decoders.Bluray.Spare.Prettify(scsiInfo.BluraySpareAreaInformation)); } - if (scsiInfo.BlurayRawDfl != null) + if(scsiInfo.BlurayRawDfl != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_dfl.bin", - "SCSI READ DISC STRUCTURE", scsiInfo.BlurayRawDfl); + "SCSI READ DISC STRUCTURE", scsiInfo.BlurayRawDfl); - if (scsiInfo.BlurayTrackResources != null) + if(scsiInfo.BlurayTrackResources != null) { DicConsole.WriteLine("Track Resources Information:\n{0}", - DiscInformation.Prettify(scsiInfo.BlurayTrackResources)); + DiscInformation.Prettify(scsiInfo.BlurayTrackResources)); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_001b.bin", - "SCSI READ DISC INFORMATION", scsiInfo.BlurayTrackResources); + "SCSI READ DISC INFORMATION", scsiInfo.BlurayTrackResources); } - if (scsiInfo.BlurayPowResources != null) + if(scsiInfo.BlurayPowResources != null) { DicConsole.WriteLine("POW Resources Information:\n{0}", - DiscInformation.Prettify(scsiInfo.BlurayPowResources)); + DiscInformation.Prettify(scsiInfo.BlurayPowResources)); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_010b.bin", - "SCSI READ DISC INFORMATION", scsiInfo.BlurayPowResources); + "SCSI READ DISC INFORMATION", scsiInfo.BlurayPowResources); } - if (scsiInfo.Toc != null) + if(scsiInfo.Toc != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_toc.bin", "SCSI READ TOC/PMA/ATIP", - scsiInfo.Toc); - if (scsiInfo.DecodedToc.HasValue) + scsiInfo.Toc); + + if(scsiInfo.DecodedToc.HasValue) DicConsole.WriteLine("TOC:\n{0}", TOC.Prettify(scsiInfo.DecodedToc)); } - if (scsiInfo.Atip != null) + if(scsiInfo.Atip != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_atip.bin", "SCSI READ TOC/PMA/ATIP", - scsiInfo.Atip); - if (scsiInfo.DecodedAtip.HasValue) + scsiInfo.Atip); + + if(scsiInfo.DecodedAtip.HasValue) DicConsole.WriteLine("ATIP:\n{0}", ATIP.Prettify(scsiInfo.DecodedAtip)); } - if (scsiInfo.CompactDiscInformation != null) + if(scsiInfo.CompactDiscInformation != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_000b.bin", - "SCSI READ DISC INFORMATION", scsiInfo.CompactDiscInformation); - if (scsiInfo.DecodedCompactDiscInformation.HasValue) + "SCSI READ DISC INFORMATION", scsiInfo.CompactDiscInformation); + + if(scsiInfo.DecodedCompactDiscInformation.HasValue) DicConsole.WriteLine("Standard Disc Information:\n{0}", - DiscInformation.Prettify000b(scsiInfo.DecodedCompactDiscInformation)); + DiscInformation.Prettify000b(scsiInfo.DecodedCompactDiscInformation)); } - if (scsiInfo.Session != null) + if(scsiInfo.Session != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_session.bin", "SCSI READ TOC/PMA/ATIP", - scsiInfo.Session); - if (scsiInfo.DecodedSession.HasValue) + scsiInfo.Session); + + if(scsiInfo.DecodedSession.HasValue) DicConsole.WriteLine("Session information:\n{0}", Session.Prettify(scsiInfo.DecodedSession)); } - if (scsiInfo.RawToc != null) + if(scsiInfo.RawToc != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_rawtoc.bin", "SCSI READ TOC/PMA/ATIP", - scsiInfo.RawToc); - if (scsiInfo.FullToc.HasValue) + scsiInfo.RawToc); + + if(scsiInfo.FullToc.HasValue) DicConsole.WriteLine("Raw TOC:\n{0}", FullTOC.Prettify(scsiInfo.RawToc)); } - if (scsiInfo.Pma != null) + if(scsiInfo.Pma != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_pma.bin", "SCSI READ TOC/PMA/ATIP", - scsiInfo.Pma); + scsiInfo.Pma); + DicConsole.WriteLine("PMA:\n{0}", PMA.Prettify(scsiInfo.Pma)); } - if (scsiInfo.CdTextLeadIn != null) + if(scsiInfo.CdTextLeadIn != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_cdtext.bin", "SCSI READ TOC/PMA/ATIP", - scsiInfo.CdTextLeadIn); - if (scsiInfo.DecodedCdTextLeadIn.HasValue) + scsiInfo.CdTextLeadIn); + + if(scsiInfo.DecodedCdTextLeadIn.HasValue) DicConsole.WriteLine("CD-TEXT on Lead-In:\n{0}", - CDTextOnLeadIn.Prettify(scsiInfo.DecodedCdTextLeadIn)); + CDTextOnLeadIn.Prettify(scsiInfo.DecodedCdTextLeadIn)); } - if (!string.IsNullOrEmpty(scsiInfo.Mcn)) DicConsole.WriteLine("MCN: {0}", scsiInfo.Mcn); + if(!string.IsNullOrEmpty(scsiInfo.Mcn)) + DicConsole.WriteLine("MCN: {0}", scsiInfo.Mcn); - if (scsiInfo.Isrcs != null) - foreach (var isrc in scsiInfo.Isrcs) + if(scsiInfo.Isrcs != null) + foreach(KeyValuePair isrc in scsiInfo.Isrcs) DicConsole.WriteLine("Track's {0} ISRC: {1}", isrc.Key, isrc.Value); - if (scsiInfo.XboxSecuritySector != null) + if(scsiInfo.XboxSecuritySector != null) DataFile.WriteTo("Media-Info command", outputPrefix, "_xbox_ss.bin", "KREON EXTRACT SS", - scsiInfo.XboxSecuritySector); + scsiInfo.XboxSecuritySector); - if (scsiInfo.DecodedXboxSecuritySector.HasValue) + if(scsiInfo.DecodedXboxSecuritySector.HasValue) DicConsole.WriteLine("Xbox Security Sector:\n{0}", SS.Prettify(scsiInfo.DecodedXboxSecuritySector)); - if (scsiInfo.XgdInfo != null) + if(scsiInfo.XgdInfo != null) { DicConsole.WriteLine("Video layer 0 size: {0} sectors", scsiInfo.XgdInfo.L0Video); DicConsole.WriteLine("Video layer 1 size: {0} sectors", scsiInfo.XgdInfo.L1Video); @@ -496,13 +538,14 @@ namespace DiscImageChef.Commands } } - if (scsiInfo.MediaSerialNumber != null) + if(scsiInfo.MediaSerialNumber != null) { DataFile.WriteTo("Media-Info command", outputPrefix, "_mediaserialnumber.bin", - "SCSI READ MEDIA SERIAL NUMBER", scsiInfo.MediaSerialNumber); + "SCSI READ MEDIA SERIAL NUMBER", scsiInfo.MediaSerialNumber); DicConsole.Write("Media Serial Number: "); - for (var i = 4; i < scsiInfo.MediaSerialNumber.Length; i++) + + for(int i = 4; i < scsiInfo.MediaSerialNumber.Length; i++) DicConsole.Write("{0:X2}", scsiInfo.MediaSerialNumber[i]); DicConsole.WriteLine(); diff --git a/DiscImageChef/Commands/MediaScan.cs b/DiscImageChef/Commands/MediaScan.cs index 6346cea4c..3cf251f27 100644 --- a/DiscImageChef/Commands/MediaScan.cs +++ b/DiscImageChef/Commands/MediaScan.cs @@ -42,52 +42,61 @@ namespace DiscImageChef.Commands { internal class MediaScanCommand : Command { - private string devicePath; - private string ibgLogPath; - private string mhddLogPath; - private bool showHelp; + string devicePath; + string ibgLogPath; + string mhddLogPath; + bool showHelp; - public MediaScanCommand() : base("media-scan", "Scans the media inserted on a device.") - { + public MediaScanCommand() : base("media-scan", "Scans the media inserted on a device.") => Options = new OptionSet { $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}", - $"{MainClass.AssemblyCopyright}", - "", - $"usage: DiscImageChef {Name} [OPTIONS] devicepath", - "", + $"{MainClass.AssemblyCopyright}", "", $"usage: DiscImageChef {Name} [OPTIONS] devicepath", "", Help, - {"mhdd-log|mw=", "Write a log of the scan in the format used by MHDD.", s => mhddLogPath = s}, - {"ibg-log|b=", "Write a log of the scan in the format used by ImgBurn.", s => ibgLogPath = s}, - {"help|h|?", "Show this message and exit.", v => showHelp = v != null} + { + "mhdd-log|mw=", "Write a log of the scan in the format used by MHDD.", s => mhddLogPath = s + }, + { + "ibg-log|b=", "Write a log of the scan in the format used by ImgBurn.", s => ibgLogPath = s + }, + { + "help|h|?", "Show this message and exit.", v => showHelp = v != null + } }; - } public override int Invoke(IEnumerable arguments) { - var extra = Options.Parse(arguments); + List extra = Options.Parse(arguments); - if (showHelp) + if(showHelp) { Options.WriteOptionDescriptions(CommandSet.Out); - return (int) ErrorNumber.HelpRequested; + + return(int)ErrorNumber.HelpRequested; } MainClass.PrintCopyright(); - if (MainClass.Debug) DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; - if (MainClass.Verbose) DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + + if(MainClass.Debug) + DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; + + if(MainClass.Verbose) + DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + Statistics.AddCommand("media-scan"); - if (extra.Count > 1) + if(extra.Count > 1) { DicConsole.ErrorWriteLine("Too many arguments."); - return (int) ErrorNumber.UnexpectedArgumentCount; + + return(int)ErrorNumber.UnexpectedArgumentCount; } - if (extra.Count == 0) + if(extra.Count == 0) { DicConsole.ErrorWriteLine("Missing device path."); - return (int) ErrorNumber.MissingArgument; + + return(int)ErrorNumber.MissingArgument; } devicePath = extra[0]; @@ -98,44 +107,57 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Scan command", "--mhdd-log={0}", mhddLogPath); DicConsole.DebugWriteLine("Media-Scan command", "--verbose={0}", MainClass.Verbose); - if (devicePath.Length == 2 && devicePath[1] == ':' && devicePath[0] != '/' && char.IsLetter(devicePath[0])) + if(devicePath.Length == 2 && + devicePath[1] == ':' && + devicePath[0] != '/' && + char.IsLetter(devicePath[0])) devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':'; Device dev; + try { dev = new Device(devicePath); - if (dev.Error) + if(dev.IsRemote) + Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem, + dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture); + + if(dev.Error) { DicConsole.ErrorWriteLine(Error.Print(dev.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } } - catch (DeviceException e) + catch(DeviceException e) { DicConsole.ErrorWriteLine(e.Message ?? Error.Print(e.LastError)); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } Statistics.AddDevice(dev); var scanner = new MediaScan(mhddLogPath, ibgLogPath, devicePath, dev); - scanner.UpdateStatus += Progress.UpdateStatus; + scanner.UpdateStatus += Progress.UpdateStatus; scanner.StoppingErrorMessage += Progress.ErrorMessage; - scanner.UpdateProgress += Progress.UpdateProgress; - scanner.PulseProgress += Progress.PulseProgress; - scanner.InitProgress += Progress.InitProgress; - scanner.EndProgress += Progress.EndProgress; + scanner.UpdateProgress += Progress.UpdateProgress; + scanner.PulseProgress += Progress.PulseProgress; + scanner.InitProgress += Progress.InitProgress; + scanner.EndProgress += Progress.EndProgress; + System.Console.CancelKeyPress += (sender, e) => { e.Cancel = true; scanner.Abort(); }; - var results = scanner.Scan(); + + ScanResults results = scanner.Scan(); DicConsole.WriteLine("Took a total of {0} seconds ({1} processing commands).", results.TotalTime, - results.ProcessingTime); + results.ProcessingTime); + DicConsole.WriteLine("Average speed: {0:F3} MiB/sec.", results.AvgSpeed); DicConsole.WriteLine("Fastest speed burst: {0:F3} MiB/sec.", results.MaxSpeed); DicConsole.WriteLine("Slowest speed burst: {0:F3} MiB/sec.", results.MinSpeed); @@ -146,23 +168,25 @@ namespace DiscImageChef.Commands DicConsole.WriteLine("{0} sectors took less than 150 ms but more than 50 ms.", results.D); DicConsole.WriteLine("{0} sectors took less than 500 ms but more than 150 ms.", results.E); DicConsole.WriteLine("{0} sectors took more than 500 ms.", results.F); - DicConsole.WriteLine("{0} sectors could not be read.", - results.UnreadableSectors.Count); - if (results.UnreadableSectors.Count > 0) - foreach (var bad in results.UnreadableSectors) + DicConsole.WriteLine("{0} sectors could not be read.", results.UnreadableSectors.Count); + + if(results.UnreadableSectors.Count > 0) + foreach(ulong bad in results.UnreadableSectors) DicConsole.WriteLine("Sector {0} could not be read", bad); DicConsole.WriteLine(); -#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator - if (results.SeekTotal != 0 || results.SeekMin != double.MaxValue || results.SeekMax != double.MinValue) -#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator - DicConsole.WriteLine( - "Testing {0} seeks, longest seek took {1:F3} ms, fastest one took {2:F3} ms. ({3:F3} ms average)", - results.SeekTimes, results.SeekMax, results.SeekMin, results.SeekTotal / 1000); + #pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator + if(results.SeekTotal != 0 || + results.SeekMin != double.MaxValue || + results.SeekMax != double.MinValue) + #pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator + DicConsole.WriteLine("Testing {0} seeks, longest seek took {1:F3} ms, fastest one took {2:F3} ms. ({3:F3} ms average)", + results.SeekTimes, results.SeekMax, results.SeekMin, results.SeekTotal / 1000); dev.Close(); - return (int) ErrorNumber.NoError; + + return(int)ErrorNumber.NoError; } } } \ No newline at end of file diff --git a/DiscImageChef/Commands/Remote.cs b/DiscImageChef/Commands/Remote.cs index d99c80e77..6afc1dce4 100644 --- a/DiscImageChef/Commands/Remote.cs +++ b/DiscImageChef/Commands/Remote.cs @@ -36,55 +36,61 @@ using System; using System.Collections.Generic; using DiscImageChef.CommonTypes.Enums; using DiscImageChef.Console; -using DiscImageChef.Devices.Remote; +using DiscImageChef.Core; using Mono.Options; +using Remote = DiscImageChef.Devices.Remote.Remote; namespace DiscImageChef.Commands { internal class RemoteCommand : Command { - private string host; - private bool showHelp; + string host; + bool showHelp; - public RemoteCommand() : base("remote", "Tests connection to a DiscImageChef Remote Server.") - { + public RemoteCommand() : base("remote", "Tests connection to a DiscImageChef Remote Server.") => Options = new OptionSet { $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}", - $"{MainClass.AssemblyCopyright}", - "", - $"usage: DiscImageChef {Name} [OPTIONS] host", - "", + $"{MainClass.AssemblyCopyright}", "", $"usage: DiscImageChef {Name} [OPTIONS] host", "", Help, - {"help|h|?", "Show this message and exit.", v => showHelp = v != null} + { + "help|h|?", "Show this message and exit.", v => showHelp = v != null + } }; - } public override int Invoke(IEnumerable arguments) { - var extra = Options.Parse(arguments); + List extra = Options.Parse(arguments); - if (showHelp) + if(showHelp) { Options.WriteOptionDescriptions(CommandSet.Out); - return (int) ErrorNumber.HelpRequested; + + return(int)ErrorNumber.HelpRequested; } MainClass.PrintCopyright(); - if (MainClass.Debug) DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; - if (MainClass.Verbose) DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; -// Statistics.AddCommand("remote"); - if (extra.Count > 1) + if(MainClass.Debug) + DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; + + if(MainClass.Verbose) + DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; + + // Statistics.AddCommand("remote"); + + if(extra.Count > 1) { DicConsole.ErrorWriteLine("Too many arguments."); - return (int) ErrorNumber.UnexpectedArgumentCount; + + return(int)ErrorNumber.UnexpectedArgumentCount; } - if (extra.Count == 0) + if(extra.Count == 0) { DicConsole.ErrorWriteLine("Missing input image."); - return (int) ErrorNumber.MissingArgument; + + return(int)ErrorNumber.MissingArgument; } host = extra[0]; @@ -96,21 +102,26 @@ namespace DiscImageChef.Commands try { var remote = new Remote(host); + + Statistics.AddRemote(remote.ServerApplication, remote.ServerVersion, remote.ServerOperatingSystem, + remote.ServerOperatingSystemVersion, remote.ServerArchitecture); + DicConsole.WriteLine("Server application: {0} {1}", remote.ServerApplication, remote.ServerVersion); + DicConsole.WriteLine("Server operating system: {0} {1} ({2})", remote.ServerOperatingSystem, - remote.ServerOperatingSystemVersion, - remote.ServerArchitecture); + remote.ServerOperatingSystemVersion, remote.ServerArchitecture); + DicConsole.WriteLine("Server maximum protocol: {0}", remote.ServerProtocolVersion); remote.Disconnect(); } - catch (Exception) + catch(Exception) { DicConsole.ErrorWriteLine("Error connecting to host."); - return (int) ErrorNumber.CannotOpenDevice; + + return(int)ErrorNumber.CannotOpenDevice; } - - return (int) ErrorNumber.NoError; + return(int)ErrorNumber.NoError; } } } \ No newline at end of file