Пример #1
0
        public static string GetDiskInformation(Disk disk)
        {
            StringBuilder builder = new StringBuilder();

            if (disk is PhysicalDisk)
            {
                PhysicalDisk physicalDisk = (PhysicalDisk)disk;
                builder.AppendLine(physicalDisk.Description);
            }
            builder.AppendFormat("Size: {0} bytes\n", disk.Size.ToString("###,###,###,###,##0"));
            builder.AppendFormat("Bytes per sector (logical): {0}\n", disk.BytesPerSector);
            if (disk is PhysicalDisk)
            {
                PhysicalDisk physicalDisk = (PhysicalDisk)disk;
                builder.AppendFormat("Geometry: Cylinders: {0}, Heads: {1}, Sectors Per Track: {2}\n", physicalDisk.Cylinders, physicalDisk.TracksPerCylinder, physicalDisk.SectorsPerTrack);
            }
            else if (disk is DiskImage)
            {
                DiskImage diskImage = (DiskImage)disk;
                builder.AppendFormat("Disk image path: {0}\n", diskImage.Path);
            }
            builder.AppendLine();

            MasterBootRecord mbr = MasterBootRecord.ReadFromDisk(disk);

            if (mbr != null)
            {
                builder.AppendFormat("Partitioning scheme: {0}\n", (mbr.IsGPTBasedDisk ? "GPT" : "MBR"));
            }
            DynamicDisk dynamicDisk = DynamicDisk.ReadFromDisk(disk);

            builder.AppendFormat("Disk type: {0}\n", ((dynamicDisk != null) ? "Dynamic Disk" : "Basic Disk"));
            if (dynamicDisk != null)
            {
                VolumeManagerDatabase database = VolumeManagerDatabase.ReadFromDisk(dynamicDisk);
                if (database != null)
                {
                    DiskRecord diskRecord = database.FindDiskByDiskGuid(dynamicDisk.PrivateHeader.DiskGuid);
                    if (diskRecord != null)
                    {
                        builder.AppendLine("Disk ID: " + diskRecord.DiskId);
                    }
                }
                builder.AppendLine("Disk GUID: " + dynamicDisk.PrivateHeader.DiskGuid);
                builder.AppendLine("Disk Group GUID: " + dynamicDisk.PrivateHeader.DiskGroupGuidString);
                builder.AppendLine();
                builder.AppendLine("Public region start sector: " + dynamicDisk.PrivateHeader.PublicRegionStartLBA);
                builder.AppendLine("Public region size (sectors): " + dynamicDisk.PrivateHeader.PublicRegionSizeLBA);
                builder.AppendLine();
                builder.AppendLine("Private region start sector: " + dynamicDisk.PrivateHeader.PrivateRegionStartLBA);
                builder.AppendLine("Private region size (sectors): " + dynamicDisk.PrivateHeader.PrivateRegionSizeLBA);
            }
            return(builder.ToString());
        }
Пример #2
0
 protected DrivePort GetDrivePort(PhysicalDisk pd)
 {
     return(new DrivePort
     {
         ports =
         {
             (int)pd.EnclosureNumber,
             (int)pd.SlotNumber
         }
     });
 }
Пример #3
0
        static PhysicalDisk GetPhysicalDisk(uint index)
        {
            PhysicalDisk disk = PhysicalDisk.GetDisks().First(d => d.Index == index);

            if (disk == null)
            {
                throw new InvalidOperationException(String.Format("Can't find physical disk index {0}", index));
            }

            return(disk);
        }
Пример #4
0
 void Disk_MouseUp(object sender, MouseEventArgs e)
 {
     if (e.Button == MouseButtons.Right)
     {
         ((CheckBox)sender).Checked = true;
         PhysicalDisk selectedDisk = (PhysicalDisk)((CheckBox)sender).Tag;
         UncheckUnselectedDisks(selectedDisk);
         ApplyExtentSelection(null);
         if (DiskRightClick != null)
         {
             Point checkBoxLocation = ((CheckBox)sender).Location;
             Point location         = new Point(checkBoxLocation.X + e.X, checkBoxLocation.Y + e.Y);
             DiskRightClick(this, new DiskRightClickEventArgs(selectedDisk, location));
         }
     }
 }
Пример #5
0
        public StorApiStatus GetSpacesDrive(string serial, ref SpacesDrive drive)
        {
            StorApiStatus  result        = StorApiStatusEnum.STOR_NO_ERROR;
            PhysicalDisk   physicalDisk  = null;
            SpacesApiError physicalDisk2 = SpacesApi.SpacesApi.GetPhysicalDisk(serial, ref physicalDisk);

            if (physicalDisk2 != SpacesApiError.Success)
            {
                return(SpacesUtil.ToStorApiStatus(physicalDisk2));
            }
            if (physicalDisk != null)
            {
                drive = this.MakeDrive(physicalDisk);
            }
            return(result);
        }
Пример #6
0
        private void OpenDisk(string device)
        {
            CreateNewDriveView(device);

            SafeFileHandle handle = WinApi.CreateFile(device,
                                                      FileAccess.Read,
                                                      FileShare.None,
                                                      IntPtr.Zero,
                                                      FileMode.Open,
                                                      0,
                                                      IntPtr.Zero);
            long         length       = WinApi.GetDiskCapactity(handle);
            long         sectorLength = WinApi.GetSectorSize(handle);
            PhysicalDisk drive        = new PhysicalDisk(handle, length, sectorLength);

            driveView.AddDrive(device, drive);

            EnableDatabaseOptions();
        }
Пример #7
0
        public async Task CreateVolume(PhysicalDisk physicalDisk)
        {
            if (physicalDisk.NoVolumes || (!physicalDisk.Volumes.Any(v => v.IsMounted) && !physicalDisk.Volumes.All(v => v.IsClean)))
            {
                try
                {
                    logger.LogInformation($"Creating primary volume on {physicalDisk}");
                    await CreatePrimaryVolume(physicalDisk);

                    logger.LogInformation($"Succeffully created primary volume on {physicalDisk}");
                }
                catch (Exception e)
                {
                    logger.LogError($"Failed to create primary volume: {e.Message}");
                }
            }
            else
            {
                logger.LogInformation($"{physicalDisk} contains mounted volume");
            }
        }
Пример #8
0
        /// <summary>
        /// Set up the performance monitor objects (CPU, Disk I/O, ...).
        /// </summary>
        private void InitializePerformanceMonitors()
        {
            try {
                _cpu = new Cpu {
                    Interval  = 250,
                    Limit     = _config.MaxCpuUsage,
                    Probation = 16,
                    LogPerformanceReadings = _config.MonitoringLogLevel,
                    Enabled = true
                };
                _cpu.LoadAboveLimit += OnLoadAboveLimit;
                _cpu.LoadBelowLimit += OnLoadBelowLimit;
            }
            catch (UnauthorizedAccessException ex) {
                Log.Error("Not enough permissions to monitor the CPU load.\nMake sure the " +
                          "service account is a member of the [Performance Monitor Users] " +
                          "system group.\nError message was: {0}", ex.Message);
                throw;
            }
            catch (Exception ex) {
                Log.Error("Unexpected error initializing CPU monitoring: {0}", ex.Message);
                throw;
            }

            try {
                _phyDisk = new PhysicalDisk {
                    Interval  = 250,
                    Limit     = (float)_config.MaxDiskQueue / 1000,
                    Probation = 16,
                    LogPerformanceReadings = _config.MonitoringLogLevel,
                    Enabled = true
                };
                _phyDisk.LoadAboveLimit += OnLoadAboveLimit;
                _phyDisk.LoadBelowLimit += OnLoadBelowLimit;
            }
            catch (Exception ex) {
                Log.Error("Unexpected error initializing PhysicalDisk monitoring: {0}", ex.Message);
                throw;
            }
        }
Пример #9
0
        public SpacesDrive MakeDrive(PhysicalDisk pd)
        {
            SpacesDrive spacesDrive = new SpacesDrive(pd.ObjectId, this);

            spacesDrive.Port        = this.GetDrivePort(pd);
            spacesDrive.Model       = pd.Model;
            spacesDrive.Serial      = pd.SerialNumber;
            spacesDrive.Revision    = pd.FirmwareVersion;
            spacesDrive.SectorSize  = pd.LogicalSectorSize;
            spacesDrive.SectorCount = 0UL;
            if (pd.LogicalSectorSize != 0UL)
            {
                spacesDrive.SectorCount = pd.Size / pd.LogicalSectorSize;
            }
            spacesDrive.IsSmartEnabled      = false;
            spacesDrive.IsSystem            = SpacesApi.SpacesApi.IsPhysicalDiskSystem(pd);
            spacesDrive.Status              = SpacesUtil.ToStorApiDriveStatus(pd);
            spacesDrive.Temperature         = 0;
            spacesDrive.Health              = pd.HealthStatus;
            spacesDrive.OperationalStatuses = pd.OperationalStatus;
            return(spacesDrive);
        }
Пример #10
0
        public static PhysicalDisk[] GetPhysicalDisks()
        {
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"))
            {
                var objects = searcher.Get().Cast <ManagementObject>();
                var disks   = new List <PhysicalDisk>();

                foreach (ManagementObject obj in objects)
                {
                    var disk = new PhysicalDisk();
                    disk.Index  = (uint)obj["Index"];
                    disk.Name   = (string)obj["Name"];
                    disk.Model  = (string)obj["Model"];
                    disk.Vendor = (string)obj["Caption"];
                    disk.Size   = (ulong)obj["Size"];
                    disk.IsSSD  = false; // The code to figure this is really frickin complex, so punting for now
                    disks.Add(disk);
                }

                return(disks.ToArray());
            }
        }
Пример #11
0
        static SafeFileHandle CreateVHD(string path, PhysicalDisk disk)
        {
            VirtualStorageType vhd_type = new VirtualStorageType();

            vhd_type.DeviceId = StorageDeviceType.Vhdx;
            vhd_type.VendorId = VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT;

            CreateVirtualDiskParameters ps = new CreateVirtualDiskParameters();

            ps.Version           = CreateVirtualDiskVersion.Version1;
            ps.SectorSizeInBytes = disk.SectorSizeInBytes;
            ps.MaximumSize       = disk.SizeInBytes + (100 * 1024 * 1024);
            ps.SourcePath        = disk.Name;
            IntPtr hDisk;
            int    error = CreateVirtualDisk(ref vhd_type, path, VirtualDiskAccessMask.All, null, CreateVirtualDiskFlag.None, 0, ref ps, IntPtr.Zero, out hDisk);

            if (error != 0)
            {
                throw new Win32Exception(error);
            }

            return(new SafeFileHandle(hDisk, true));
        }
Пример #12
0
        private void comboSourceDisk_SelectedIndexChanged(object sender, EventArgs e)
        {
            int physicalDiskIndex = ((KeyValuePair <int, string>)comboSourceDisk.SelectedItem).Key;

            if (physicalDiskIndex == -1) // VHD
            {
                DialogResult openFileResult = openVirtualDiskFileDialog.ShowDialog();
                if (openFileResult != DialogResult.OK)
                {
                    comboSourceDisk.SelectedIndex = 0;
                }
                else
                {
                    lblSourceDiskSerialNumber.Text = openVirtualDiskFileDialog.FileName;
                }
            }
            else
            {
                PhysicalDisk disk = null;
                try
                {
                    disk = new PhysicalDisk(physicalDiskIndex);
                }
                catch (DriveNotFoundException)
                {
                }

                if (disk != null)
                {
                    lblSourceDiskSerialNumber.Text = "S/N: " + disk.SerialNumber;
                }
                else
                {
                    lblSourceDiskSerialNumber.Text = "Error: Disk not found";
                }
            }
        }
Пример #13
0
        public static DynamicDisk FindDisk(Guid diskGuid)
        {
            List <int> diskIndexList = PhysicalDiskControl.GetPhysicalDiskIndexList();

            foreach (int diskIndex in diskIndexList)
            {
                PhysicalDisk disk;
                try
                {
                    disk = new PhysicalDisk(diskIndex); // will throw an exception if disk is not valid
                }
                catch (DriveNotFoundException)
                {
                    // The disk must have been removed from the system
                    continue;
                }
                catch (DeviceNotReadyException)
                {
                    continue;
                }
                catch (SharingViolationException) // skip this disk, it's probably being used
                {
                    continue;
                }

                DynamicDisk dynamicDisk = DynamicDisk.ReadFromDisk(disk);
                if (dynamicDisk != null)
                {
                    if (dynamicDisk.DiskGuid == diskGuid)
                    {
                        return(dynamicDisk);
                    }
                }
            }
            return(null);
        }
Пример #14
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (m_isBusy)
            {
                btnStart.Enabled     = false;
                btnStart.Text        = "Stopping";
                groupOptions.Enabled = false;
                Thread thread = new Thread(delegate()
                {
                    m_diskCopier.Abort = true;
                    while (m_isBusy)
                    {
                        Thread.Sleep(100);
                    }
                    if (!m_isClosing)
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            EnableUI();
                            btnStart.Enabled = true;
                        });
                    }
                });
                thread.Start();
            }
            else
            {
                if (comboSourceDisk.SelectedItem == null)
                {
                    return;
                }
                int  sourceDiskIndex = ((KeyValuePair <int, string>)comboSourceDisk.SelectedItem).Key;
                int  targetDiskIndex = ((KeyValuePair <int, string>)comboTargetDisk.SelectedItem).Key;
                Disk sourceDisk      = null;
                Disk targetDisk      = null;
                if (sourceDiskIndex == -1)
                {
                    string path = openVirtualDiskFileDialog.FileName;
                    try
                    {
                        sourceDisk = new VirtualHardDisk(path, true);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show("Failed to open the virtual disk: " + ex.Message, "Error");
                        return;
                    }
                }
                else
                {
                    try
                    {
                        sourceDisk = new PhysicalDisk(sourceDiskIndex);
                    }
                    catch (DriveNotFoundException)
                    {
                        MessageBox.Show("Source disk not found", "Error");
                        return;
                    }
                }

                if (targetDiskIndex == -1)
                {
                    string path = saveVirtualDiskFileDialog.FileName;;
                    try
                    {
                        if (chkWriteZeros.Checked)
                        {
                            targetDisk = VirtualHardDisk.CreateFixedDisk(path, sourceDisk.Size);
                        }
                        else
                        {
                            targetDisk = VirtualHardDisk.CreateDynamicDisk(path, sourceDisk.Size);
                        }
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show("Failed to create the virtual disk: " + ex.Message, "Error");
                        return;
                    }
                }
                else
                {
                    try
                    {
                        targetDisk = new PhysicalDisk(targetDiskIndex);
                    }
                    catch (DriveNotFoundException)
                    {
                        MessageBox.Show("Target disk not found", "Error");
                        return;
                    }
                }
                DisableUI();
                Thread thread = new Thread(delegate()
                {
                    m_isBusy = true;
                    CopyDisk(sourceDisk, targetDisk);
                    m_isBusy = false;
                    if (m_isClosing)
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            this.Close();
                        });
                    }
                    else
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            EnableUI();
                        });
                    }
                });
                thread.Start();
            }
        }
Пример #15
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            PhysicalDisk selectedDisk;

            if (listPhysicalDisks.SelectedItems.Count > 0)
            {
                selectedDisk = (PhysicalDisk)listPhysicalDisks.SelectedItems[0].Tag;
            }
            else
            {
                MessageBox.Show("No disk was selected", "Error");
                return;
            }
            if (!chkReadOnly.Checked)
            {
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    bool isDiskReadOnly;
                    bool isOnline = selectedDisk.GetOnlineStatus(out isDiskReadOnly);
                    if (isDiskReadOnly)
                    {
                        MessageBox.Show("The selected disk is set to readonly", "Error");
                        return;
                    }

                    if (isOnline)
                    {
                        DialogResult result = MessageBox.Show("The selected disk will now be taken offline. OK?", String.Empty, MessageBoxButtons.OKCancel);
                        if (result == DialogResult.OK)
                        {
                            bool success = selectedDisk.SetOnlineStatus(false);
                            if (!success)
                            {
                                MessageBox.Show("Was not able to take the disk offline", "Error");
                                return;
                            }
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                else
                {
                    if (DynamicDisk.IsDynamicDisk(selectedDisk))
                    {
                        // The user will probably want to stop the Logical Disk Manager services (vds, dmadmin, dmserver)
                        // and lock all dynamic disks and dynamic volumes before whatever he's doing.
                        // Modifications the the LDM database should be applied to all dynamic disks.
                        DialogResult result = MessageBox.Show("The dynamic disk database will likely be corrupted, Continue?", "Warning", MessageBoxButtons.YesNo);
                        if (result != DialogResult.Yes)
                        {
                            return;
                        }
                    }
                    else
                    {
                        // Locking a disk does not prevent Windows from accessing mounted volumes on it. (it does prevent creation of new volumes).
                        // For basic disks we need to lock the Disk and Volumes, and we should also call UpdateDiskProperties() after releasing the lock.
                        LockStatus status = LockHelper.LockBasicDiskAndVolumesOrNone(selectedDisk);
                        if (status == LockStatus.CannotLockDisk)
                        {
                            MessageBox.Show("Unable to lock the disk", "Error");
                            return;
                        }
                        else if (status == LockStatus.CannotLockVolume)
                        {
                            MessageBox.Show("Unable to lock one of the volumes on the disk", "Error");
                            return;
                        }
                    }
                }
            }
            if (chkReadOnly.Checked)
            {
                selectedDisk = new PhysicalDisk(selectedDisk.PhysicalDiskIndex, true);
            }
            m_selectedDisk    = selectedDisk;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Пример #16
0
        static SafeFileHandle CreateVHD(string path, PhysicalDisk disk)
        {
            VirtualStorageType vhd_type = new VirtualStorageType();
            vhd_type.DeviceId = StorageDeviceType.Vhdx;
            vhd_type.VendorId = VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT;

            CreateVirtualDiskParameters ps = new CreateVirtualDiskParameters();
            ps.Version = CreateVirtualDiskVersion.Version1;
            ps.SectorSizeInBytes = disk.SectorSizeInBytes;
            ps.MaximumSize = disk.SizeInBytes + (100 * 1024 * 1024);
            ps.SourcePath = disk.Name;
            IntPtr hDisk;
            int error = CreateVirtualDisk(ref vhd_type, path, VirtualDiskAccessMask.All, null, CreateVirtualDiskFlag.None, 0, ref ps, IntPtr.Zero, out hDisk);
            if (error != 0)
            {
                throw new Win32Exception(error);
            }

            return new SafeFileHandle(hDisk, true);
        }
        public static void DetailCommand(string[] args)
        {
            if (args.Length == 2)
            {
                switch (args[1].ToLower())
                {
                case "disk":
                {
                    Console.WriteLine();
                    if (m_selectedDisk != null)
                    {
                        Console.WriteLine("Size: {0} bytes", m_selectedDisk.Size.ToString("###,###,###,###,##0"));
                        if (m_selectedDisk is PhysicalDisk)
                        {
                            PhysicalDisk disk = (PhysicalDisk)m_selectedDisk;
                            Console.WriteLine("Geometry: Heads: {0}, Cylinders: {1}, Sectors Per Track: {2}", disk.TracksPerCylinder, disk.Cylinders, disk.SectorsPerTrack);
                            Console.WriteLine();
                        }
                        else if (m_selectedDisk is DiskImage)
                        {
                            DiskImage disk = (DiskImage)m_selectedDisk;
                            Console.WriteLine("Disk image path: {0}", disk.Path);
                            Console.WriteLine();
                        }

                        MasterBootRecord mbr = MasterBootRecord.ReadFromDisk(m_selectedDisk);
                        if (mbr != null)
                        {
                            Console.WriteLine("Partitioning scheme: " + (mbr.IsGPTBasedDisk ? "GPT" : "MBR"));
                        }
                        DynamicDisk dynamicDisk = DynamicDisk.ReadFromDisk(m_selectedDisk);
                        Console.WriteLine("Disk type: " + ((dynamicDisk != null) ? "Dynamic Disk" : "Basic Disk"));
                    }
                    else
                    {
                        Console.WriteLine("No disk has been selected.");
                    }
                    break;
                }

                case "volume":
                case "partition":
                {
                    Console.WriteLine();
                    if (m_selectedVolume != null)
                    {
                        Console.WriteLine("Volume size: {0} bytes", m_selectedVolume.Size.ToString("###,###,###,###,##0"));
                        if (m_selectedVolume is GPTPartition)
                        {
                            Console.WriteLine("Partition name: {0}", ((GPTPartition)m_selectedVolume).PartitionName);
                        }

                        Guid?windowsVolumeGuid = WindowsVolumeHelper.GetWindowsVolumeGuid(m_selectedVolume);
                        if (windowsVolumeGuid.HasValue)
                        {
                            List <string> mountPoints = WindowsVolumeManager.GetMountPoints(windowsVolumeGuid.Value);
                            foreach (string volumePath in mountPoints)
                            {
                                Console.WriteLine("Volume path: {0}", volumePath);
                            }
                            bool isMounted = WindowsVolumeManager.IsMounted(windowsVolumeGuid.Value);
                            Console.WriteLine("Mounted: {0}", isMounted);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No volume has been selected.");
                    }
                    break;
                }

                default:
                    Console.WriteLine("Invalid argument.");
                    HelpDetail();
                    break;
                }
            }
            else if (args.Length > 2)
            {
                Console.WriteLine("Too many arguments.");
                HelpDetail();
            }
            else
            {
                HelpDetail();
            }
        }
Пример #18
0
        public static void AttachCommand(string[] args)
        {
            if (m_server != null)
            {
                Console.WriteLine("Server is already running");
                return;
            }

            if (args.Length >= 2)
            {
                KeyValuePairList <string, string> parameters = ParseParameters(args, 2);
                if (!VerifyParameters(parameters, "vdisk", "disk", "volume", "readonly", "target"))
                {
                    Console.WriteLine();
                    Console.WriteLine("Invalid parameter");
                    HelpAttach();
                    return;
                }

                switch (args[1].ToLower())
                {
                case "vdisk":
                {
                    if (m_selectedDisk == null)
                    {
                        Console.WriteLine("No disk has been selected");
                        break;
                    }

                    if (!(m_selectedDisk is DiskImage))
                    {
                        Console.WriteLine("Selected disk is not a disk image");
                        break;
                    }

                    DiskImage disk = (DiskImage)m_selectedDisk;
                    string    defaultStorageTargetName = Path.GetFileNameWithoutExtension(disk.Path);
                    string    defaultTargetName        = DefaultTargetIQN + ":" + defaultStorageTargetName.Replace(" ", ""); // spaces are not allowed
                    AttachISCSIDisk(disk, defaultTargetName, parameters);
                    break;
                }

                case "disk":
                {
                    if (m_selectedDisk == null)
                    {
                        Console.WriteLine("Error: No disk has been selected.");
                        break;
                    }

                    if (!(m_selectedDisk is PhysicalDisk))
                    {
                        Console.WriteLine("Error: The selected disk is not a physical disk.");
                        break;
                    }

                    bool         isAttachmentReadOnly = parameters.ContainsKey("readonly");
                    PhysicalDisk disk = (PhysicalDisk)m_selectedDisk;
                    if (!isAttachmentReadOnly)
                    {
                        if (Environment.OSVersion.Version.Major >= 6)
                        {
                            bool isDiskReadOnly;
                            bool isOnline = disk.GetOnlineStatus(out isDiskReadOnly);
                            if (isOnline)
                            {
                                Console.WriteLine();
                                Console.WriteLine("Error: The selected disk must be taken offline.");
                                break;
                            }

                            if (!isAttachmentReadOnly && isDiskReadOnly)
                            {
                                Console.WriteLine();
                                Console.WriteLine("Error: The selected disk is set to readonly!");
                                break;
                            }
                        }
                        else
                        {
                            Console.WriteLine();
                            // Locking mechanism is not implemented
                            Console.Write("Warning: if a volume on this disk is mounted locally, data corruption may occur!");
                        }
                    }
                    string defaultStorageTargetName = string.Format("disk{0}", disk.PhysicalDiskIndex);
                    string defaultTargetName        = DefaultTargetIQN + ":" + defaultStorageTargetName;
                    AttachISCSIDisk(disk, defaultTargetName, parameters);
                    break;
                }

                case "volume":
                {
                    if (m_selectedVolume == null)
                    {
                        Console.WriteLine("No volume has been selected.");
                        break;
                    }

                    VolumeDisk virtualDisk          = new VolumeDisk(m_selectedVolume);
                    string     defaultTargetName    = DefaultTargetIQN + ":Volume";
                    bool       isAttachmentReadOnly = parameters.ContainsKey("readonly");
                    if (!isAttachmentReadOnly)
                    {
                        if (Environment.OSVersion.Version.Major >= 6)
                        {
                            if (m_selectedVolume is DynamicVolume)
                            {
                                foreach (DiskExtent extent in ((DynamicVolume)m_selectedVolume).Extents)
                                {
                                    if (extent.Disk is PhysicalDisk)
                                    {
                                        bool isDiskReadOnly;
                                        bool isOnline = ((PhysicalDisk)extent.Disk).GetOnlineStatus(out isDiskReadOnly);
                                        if (isOnline)
                                        {
                                            Console.WriteLine("Error: All disks containing the volume must be taken offline.");
                                            return;
                                        }

                                        if (isDiskReadOnly)
                                        {
                                            Console.WriteLine("Error: A disk containing the volume is set to readonly.");
                                            return;
                                        }
                                    }
                                }
                            }
                            else if (m_selectedVolume is Partition)
                            {
                                Disk disk = ((Partition)m_selectedVolume).Disk;
                                if (disk is PhysicalDisk)
                                {
                                    bool isDiskReadOnly;
                                    bool isOnline = ((PhysicalDisk)disk).GetOnlineStatus(out isDiskReadOnly);

                                    if (isOnline)
                                    {
                                        Console.WriteLine("Error: The disk containing the volume must be taken offline.");
                                        return;
                                    }

                                    if (isDiskReadOnly)
                                    {
                                        Console.WriteLine("Error: The disk containing the volume is set to readonly.");
                                        return;
                                    }
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine();
                            // Locking mechanism is not implemented
                            Console.WriteLine("Warning: if this volume is mounted locally, data corruption may occur!");
                        }
                    }
                    AttachISCSIDisk(virtualDisk, defaultTargetName, parameters);
                    break;
                }

                default:
                {
                    Console.WriteLine();
                    Console.WriteLine("Invalid argument.");
                    HelpAttach();
                    break;
                }
                }
            }
            else
            {
                HelpAttach();
            }
        }
Пример #19
0
        protected override Int32 Execute()
        {
            try
            {
                if (1 == _commandLineParser.FileNames.Length)
                {
                    var deviceName = _commandLineParser.FileNames[0];

                    if (deviceName.EndsWith(":"))
                    {
                        PrintLogicalDiskInformation(deviceName);
                    }
                    else
                    {
                        PrintPhysicalDiskInformation(deviceName);
                    }
                }
                else if (_commandLineParser.IsOptionSet("p"))
                {
                    if (_commandLineParser.OptionHasValue("p"))
                    {
                        var deviceName = _commandLineParser.GetOptionString("p");

                        if (deviceName.Equals("all", StringComparison.InvariantCultureIgnoreCase))
                        {
                            foreach (var deviceName1 in PhysicalDisk.GetDeviceNames())
                            {
                                PrintPhysicalDiskInformation(deviceName1);
                            }
                        }
                        else
                        {
                            UInt32 diskNumber;
                            if (UInt32.TryParse(deviceName, out diskNumber))
                            {
                                deviceName = PhysicalDisk.FormatDeviceName(diskNumber);
                            }

                            PrintPhysicalDiskInformation(deviceName);
                        }
                    }
                    else
                    {
                        PrintArray(PhysicalDisk.GetDeviceNames());
                    }
                }
                else if (_commandLineParser.IsOptionSet("l"))
                {
                    if (_commandLineParser.OptionHasValue("l"))
                    {
                        var deviceName = _commandLineParser.GetOptionString("l");

                        if (deviceName.Equals("all", StringComparison.InvariantCultureIgnoreCase))
                        {
                            foreach (var deviceName1 in LogicalDisk.GetDeviceNames())
                            {
                                PrintLogicalDiskInformation(deviceName1);
                            }
                        }
                        else
                        {
                            if (1 == deviceName.Length)
                            {
                                var volume = Char.ToUpper(deviceName[0]);
                                if ((volume >= 'A') && (volume <= 'Z'))
                                {
                                    deviceName = LogicalDisk.FormatDeviceName(volume);
                                }
                            }

                            PrintLogicalDiskInformation(deviceName);
                        }
                    }
                    else
                    {
                        PrintArray(LogicalDisk.GetDeviceNames());
                    }
                }
                else
                {
                    Help();
                }

                return(0);
            }
            catch (Exception ex)
            {
                Print("Error reading disk information: {0}", ex.Message);
                return(1);
            }
        }
Пример #20
0
        private void PrintPhysicalDiskInformation(String deviceName)
        {
            using (var physicalDisk = new PhysicalDisk(deviceName, true))
            {
                Console.WriteLine("Physical disk {0}", physicalDisk.DeviceName);

                physicalDisk.ReadDiskInformation();

                Console.WriteLine("\nDISK_GEOMETRY:");
                Console.WriteLine("Cylinders:\t\t{0:N0}", physicalDisk.DiskGeometry.Cylinders);
                Console.WriteLine("MediaType:\t\t0x{0:X2} ({1})", physicalDisk.DiskGeometry.MediaType, PhysicalDisk.GetMediaTypeString(physicalDisk.DiskGeometry.MediaType));
                Console.WriteLine("TracksPerCylinder:\t{0:N0}", physicalDisk.DiskGeometry.TracksPerCylinder);
                Console.WriteLine("SectorsPerTrack:\t{0:N0}", physicalDisk.DiskGeometry.SectorsPerTrack);
                Console.WriteLine("BytesPerSector:\t\t{0:N0}", physicalDisk.DiskGeometry.BytesPerSector);

                var diskSize = physicalDisk.DiskGeometry.Cylinders * physicalDisk.DiskGeometry.TracksPerCylinder * physicalDisk.DiskGeometry.SectorsPerTrack * physicalDisk.DiskGeometry.BytesPerSector;
                Console.WriteLine("\nDisk size:\t\t{0:N0} bytes", diskSize);

                Console.WriteLine("\nDRIVE_LAYOUT_INFORMATION:");
                Console.WriteLine("PartitionCount:\t{0}", physicalDisk.DriveLayoutInformation.PartitionCount);
                Console.WriteLine("Signature:\t0x{0:X8}", physicalDisk.DriveLayoutInformation.Signature);

                for (var i = 0; i < physicalDisk.PartitionInformation.Length; i++)
                {
                    PrintPartitionInformation(physicalDisk.PartitionInformation[i]);
                }
            }
        }
Пример #21
0
        public static void SelectCommand(string[] args)
        {
            if (args.Length == 1)
            {
                HelpSelect();
                return;
            }

            switch (args[1].ToLower())
            {
            case "disk":
            {
                if (args.Length == 3)
                {
                    int diskIndex = Conversion.ToInt32(args[2], -1);
                    if (diskIndex >= 0)
                    {
                        PhysicalDisk disk = null;
                        try
                        {
                            disk = new PhysicalDisk(diskIndex);
                        }
                        catch
                        {
                            Console.WriteLine();
                            Console.WriteLine("Error: Invalid disk number");
                        }

                        if (disk != null)
                        {
                            m_selectedDisk = disk;
                        }
                    }
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine("Error: Invalid number of arguments");
                }
                break;
            }

            case "vdisk":
            {
                if (args.Length == 3)
                {
                    KeyValuePairList <string, string> parameters = ParseParameters(args, 2);
                    if (parameters.ContainsKey("file"))
                    {
                        string path = parameters.ValueOf("file");
                        if (new FileInfo(path).Exists)
                        {
                            try
                            {
                                m_selectedDisk = DiskImage.GetDiskImage(path);
                            }
                            catch (InvalidDataException)
                            {
                                Console.WriteLine("Invalid virtual disk format");
                            }
                            catch (NotImplementedException)
                            {
                                Console.WriteLine("Unsupported virtual disk format");
                            }
                            catch (IOException ex)
                            {
                                Console.WriteLine("Cannot read file: " + ex.Message);
                            }
                        }
                        else
                        {
                            Console.WriteLine("File not found: \"{0}\"", path);
                        }
                    }
                    else
                    {
                        Console.WriteLine();
                        Console.WriteLine("Error: Invalid argument");
                    }
                }
                else
                {
                    Console.WriteLine("Error: Invalid number of arguments");
                }
                break;
            }

            case "partition":
            {
                if (m_selectedDisk != null)
                {
                    if (args.Length == 3)
                    {
                        int partitionIndex          = Conversion.ToInt32(args[2], -1);
                        List <Partition> partitions = BasicDiskHelper.GetPartitions(m_selectedDisk);
                        if (partitionIndex >= 0 && partitionIndex < partitions.Count)
                        {
                            m_selectedVolume = partitions[partitionIndex];
                        }
                        else
                        {
                            Console.WriteLine("Error: Invalid partition number");
                        }
                    }
                    else
                    {
                        Console.WriteLine();
                        Console.WriteLine("Error: Partition number was not specified");
                    }
                }
                else
                {
                    Console.WriteLine("No disk has been selected");
                }
                break;
            }

            case "volume":
            {
                if (args.Length == 3)
                {
                    List <Volume> volumes;
                    try
                    {
                        volumes = WindowsVolumeHelper.GetVolumes();
                    }
                    catch
                    {
                        volumes = new List <Volume>();
                    }

                    int volumeIndex = Conversion.ToInt32(args[2], -1);
                    if (volumeIndex >= 0 && volumeIndex < volumes.Count)
                    {
                        m_selectedVolume = volumes[volumeIndex];
                    }
                    else
                    {
                        Console.WriteLine();
                        Console.WriteLine("Error: Invalid volume number");
                    }
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine("Error: Volume number was not specified");
                }
                break;
            }

            default:
                HelpSelect();
                break;
            }
        }
            /// <summary>
            /// class constructor
            /// </summary>
            public PhysicalDisks()
            {
                try
                {
                    ManagementObjectSearcher _HDDS = new ManagementObjectSearcher("select * from Win32_DiskDrive");

                    if (_HDDS.Get().Count == -1)
                    {
                        throw new Exception("Could not get HDD(s) information.");
                    }


                    // Iterate over Physical Disks
                    foreach (ManagementObject _Hdd in _HDDS.Get())
                    {
                        PhysicalDisk Hdd_Info = new PhysicalDisk();

                        // Iterate over physical disk info
                        foreach (PropertyData PC in _Hdd.Properties)
                        {
                            if (PC.Value != null)
                            {
                                if (PC.Name == "InterfaceType")
                                {
                                    Hdd_Info.Disk_Interface_Type = (string)_Hdd[PC.Name];
                                }
                                if (PC.Name == "MediaType")
                                {
                                    Hdd_Info.Disk_Media_Type = (string)_Hdd[PC.Name];
                                }
                                if (PC.Name == "Name")
                                {
                                    Hdd_Info.Disk_Name = (string)_Hdd[PC.Name];
                                }
                                if (PC.Name == "Partitions")
                                {
                                    Hdd_Info.Disk_Partition_Count = (uint)_Hdd[PC.Name];
                                }
                                if (PC.Name == "SerialNumber")
                                {
                                    Hdd_Info.Disk_Serial_Number = (string)_Hdd[PC.Name];
                                }
                                if (PC.Name == "Size")
                                {
                                    Hdd_Info.Disk_Size = Convert.ToUInt64(_Hdd[PC.Name]);
                                }
                                if (PC.Name == "Index")
                                {
                                    Hdd_Info.Disk_Index = Convert.ToUInt32(_Hdd[PC.Name]);
                                }
                            }
                        }



                        // get physical disk partition information
                        ManagementObjectSearcher partition_info;

                        if (new ManagementObjectSearcher("select * from Win32_DiskPartition where DiskIndex="
                                                         + Hdd_Info.Disk_Index.ToString()).Get().Count != 0)
                        {
                            partition_info = new ManagementObjectSearcher("select * from Win32_DiskPartition where DiskIndex=" + Hdd_Info.Disk_Index.ToString());

                            // Iterate over Physical disk partitions
                            foreach (ManagementObject ObjPartition in partition_info.Get())
                            {
                                PhysicalDisk.Partition hdd_partition_info = new PhysicalDisk.Partition();

                                // Iterate over Physical disk partition information
                                foreach (PropertyData PC in ObjPartition.Properties)
                                {
                                    if (PC.Value != null)
                                    {
                                        if (PC.Name == "Name")
                                        {
                                            hdd_partition_info.Partition_Name = (string)ObjPartition[PC.Name];
                                        }

                                        if (PC.Name == "BootPartition")
                                        {
                                            hdd_partition_info.Is_Boot_Partition = (bool)ObjPartition[PC.Name];
                                        }

                                        if (PC.Name == "PrimaryPartition")
                                        {
                                            hdd_partition_info.Is_Primary_Partition = (bool)ObjPartition[PC.Name];
                                        }

                                        if (PC.Name == "Size")
                                        {
                                            hdd_partition_info.Partition_Size = Convert.ToUInt64(ObjPartition[PC.Name]);
                                        }

                                        if (PC.Name == "Type")
                                        {
                                            hdd_partition_info.Partition_Type = (string)ObjPartition[PC.Name];
                                        }
                                    }
                                }

                                // Add Partition information to the list
                                Hdd_Info.Disk_Partitions.Add(hdd_partition_info);
                            }
                        }

                        // Add Physyical disk to the Physical Disks list
                        Physical_Disks.Add(Hdd_Info); // add current Disk Drive information to the list
                    }
                }

                catch (Exception ex)
                {
                    throw ex;
                }
            }
Пример #23
0
        private static void Main(string[] args)
        {
            var loglevel = LogLevel.Debug;

            if (args.Length > 0 && args[0] == "trace")
            {
                loglevel = LogLevel.Trace;
            }
            var logConfig        = new LoggingConfiguration();
            var logTargetConsole = new ConsoleTarget {
                Name   = "console",
                Header = "AutoTx Diagnostics",
                Layout = @"${time} [${level}] ${message}",
            };

            logConfig.AddTarget(logTargetConsole);
            var logRuleConsole = new LoggingRule("*", loglevel, logTargetConsole);

            logConfig.LoggingRules.Add(logRuleConsole);
            LogManager.Configuration = logConfig;

            // set the default performance monitors:
            var perfMonitors = new[] { "CPU", "PhysicalDisk" };

            // if requested explicitly as a command line parameter, override them:
            if (args.Length > 1)
            {
                perfMonitors = args[1].Split(',');
            }

            var commonAssembly    = Assembly.GetAssembly(typeof(Cpu));
            var commonVersionInfo = FileVersionInfo.GetVersionInfo(commonAssembly.Location);

            Log.Info("ATxCommon library version: {0}", commonVersionInfo.ProductVersion);

            Log.Debug("Free space on drive [C:]: " + Conv.BytesToString(SystemChecks.GetFreeDriveSpace("C:")));

            if (perfMonitors.Contains("CPU"))
            {
                Log.Info("Watching CPU load using ATxCommon.Monitoring...");
                var cpu = new Cpu {
                    Interval  = 250,
                    Limit     = 50,
                    Probation = 4, // 4 * 250 ms = 1 second
                    LogPerformanceReadings = LogLevel.Info,
                    Enabled = true
                };
            }

            if (perfMonitors.Contains("PhysicalDisk"))
            {
                Log.Info("Watching I/O load using ATxCommon.Monitoring...");
                var disk = new PhysicalDisk {
                    Interval  = 250,
                    Limit     = 0.25F,
                    Probation = 4, // 4 * 250 ms = 1 second
                    LogPerformanceReadings = LogLevel.Info,
                    Enabled = true
                };
            }

            while (true)
            {
                System.Threading.Thread.Sleep(10000);
            }
        }
Пример #24
0
        private PhysicalDisk method_4(string string_1)
        {
            PhysicalDisk disk = new PhysicalDisk {
                Extents      = new VOLUMEDISKEXTENTS(),
                Adapter      = new STORAGE_ADAPTER_DESCRIPTOR(),
                DeviceID     = new STORAGE_DEVICE_ID_DESCRIPTOR(),
                Device       = new STORAGE_DEVICE_DESCRIPTOR(),
                Version      = new GETVERSIONOUTPARAMS(),
                Params       = new SENDCMDOUTPARAMS(),
                SerialNumber = string.Empty,
                Firmware     = string.Empty,
                Model        = string.Empty
            };

            char[]         trimChars = new char[] { '\\' };
            SafeFileHandle handle    = Class1.CreateFileW(Class3.smethod_10(0) + Path.GetPathRoot(string_1).TrimEnd(trimChars), 0xc0000000, 3, IntPtr.Zero, 3, 0x80, IntPtr.Zero);

            try
            {
                uint    num     = 0;
                int     cb      = Marshal.SizeOf(disk.Extents);
                IntPtr  ptr     = Marshal.AllocHGlobal(cb);
                Struct0 struct2 = new Struct0();
                uint    num3    = this.method_0(0x56, 0, 0, 0);
                if (Class1.DeviceIoControl_1(handle, num3, IntPtr.Zero, 0, ptr, cb, ref num, 0))
                {
                    disk.Extents = (VOLUMEDISKEXTENTS)Marshal.PtrToStructure(ptr, typeof(VOLUMEDISKEXTENTS));
                    disk.Number  = Convert.ToByte(disk.Extents.diskNumber);
                }
                cb             = Marshal.SizeOf(disk.Adapter);
                ptr            = Marshal.AllocHGlobal(cb);
                struct2.uint_0 = 1;
                struct2.uint_1 = 0;
                if (Class1.DeviceIoControl(handle, 0x2d1400, struct2, Marshal.SizeOf(struct2), ptr, cb, ref num, 0))
                {
                    disk.Adapter = (STORAGE_ADAPTER_DESCRIPTOR)Marshal.PtrToStructure(ptr, typeof(STORAGE_ADAPTER_DESCRIPTOR));
                }
                cb             = Marshal.SizeOf(disk.DeviceID);
                ptr            = Marshal.AllocHGlobal(cb);
                struct2.uint_0 = 2;
                struct2.uint_1 = 0;
                if (Class1.DeviceIoControl(handle, 0x2d1400, struct2, Marshal.SizeOf(struct2), ptr, cb, ref num, 0))
                {
                    disk.DeviceID = (STORAGE_DEVICE_ID_DESCRIPTOR)Marshal.PtrToStructure(ptr, typeof(STORAGE_DEVICE_ID_DESCRIPTOR));
                }
                cb             = Marshal.SizeOf(disk.Device);
                ptr            = Marshal.AllocHGlobal(cb);
                struct2.uint_0 = 0;
                struct2.uint_1 = 0;
                if (Class1.DeviceIoControl(handle, 0x2d1400, struct2, Marshal.SizeOf(struct2), ptr, cb, ref num, 0))
                {
                    disk.Device = (STORAGE_DEVICE_DESCRIPTOR)Marshal.PtrToStructure(ptr, typeof(STORAGE_DEVICE_DESCRIPTOR));
                    string str2 = Encoding.ASCII.GetString(disk.Device.RawDeviceProperties);
                    int    num4 = Marshal.SizeOf(disk.Device) - disk.Device.RawDeviceProperties.Length;
                    if (disk.Device.ProductIdOffset > 0)
                    {
                        char[] chArray2 = new char[2];
                        chArray2[1] = ' ';
                        disk.Model  = str2.Substring(disk.Device.ProductIdOffset - num4, 20).Trim(chArray2);
                    }
                    if (disk.Device.ProductRevisionOffset > 0)
                    {
                        char[] chArray3 = new char[2];
                        chArray3[1]   = ' ';
                        disk.Firmware = str2.Substring(disk.Device.ProductRevisionOffset - num4, 8).Trim(chArray3);
                    }
                    if (disk.Device.SerialNumberOffset > 0)
                    {
                        char[] chArray4 = new char[2];
                        chArray4[1]       = ' ';
                        disk.SerialNumber = str2.Substring(disk.Device.SerialNumberOffset - num4, 40).Trim(chArray4);
                    }
                    if ((disk.SerialNumber != null) && (disk.SerialNumber.Length == 40))
                    {
                        disk.SerialNumber = this.method_3(disk.SerialNumber);
                    }
                    disk.RemovableMedia = Convert.ToBoolean(disk.Device.RemovableMedia);
                }
                cb  = Marshal.SizeOf(disk.Version);
                ptr = Marshal.AllocHGlobal(cb);
                if (Class1.DeviceIoControl_1(handle, 0x74080, IntPtr.Zero, 0, ptr, cb, ref num, 0))
                {
                    disk.Version = (GETVERSIONOUTPARAMS)Marshal.PtrToStructure(ptr, typeof(GETVERSIONOUTPARAMS));
                    if ((disk.Version.fCapabilities & 4L) > 0L)
                    {
                        SENDCMDINPARAMS sendcmdinparams = new SENDCMDINPARAMS();
                        sendcmdinparams.DriveRegs.Command = 0xec;
                        sendcmdinparams.DriveNumber       = disk.Number;
                        sendcmdinparams.BufferSize        = 0x200;
                        if (Class1.DeviceIoControl(handle, 0x7c088, sendcmdinparams, Marshal.SizeOf(sendcmdinparams), ptr, cb, ref num, 0))
                        {
                            disk.Params       = (SENDCMDOUTPARAMS)Marshal.PtrToStructure(ptr, typeof(SENDCMDOUTPARAMS));
                            disk.Model        = this.method_2(disk.Params.IDS.ModelNumber).Trim();
                            disk.Firmware     = this.method_2(disk.Params.IDS.FirmwareRevision).Trim();
                            disk.SerialNumber = this.method_2(disk.Params.IDS.SerialNumber).Trim();
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (handle != null)
                {
                    handle.Dispose();
                }
            }
            return(disk);
        }
Пример #25
0
        private async Task CreatePrimaryVolume(PhysicalDisk physicalDisk)
        {
            await processInvoker.InvokeSudoProcess("parted", physicalDisk.DevPath.Path, "--script", "--", "mklabel", "gpt");

            await processInvoker.InvokeSudoProcess("parted", physicalDisk.DevPath.Path, "--script", "--", "mkpart", "primary", "0%", "100%");
        }
Пример #26
0
        private void PerformTest(int physicalDiskIndex, TestName testName)
        {
            PhysicalDisk disk = new PhysicalDisk(physicalDiskIndex);

            m_startTime = DateTime.Now;
            ClearLog();
            AddToLog("Hard Disk Validator {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
            AddToLog("Starting {0} Test", GetTestTitle(testName));
            AddToLog("Disk: {0}, S/N: {1}", disk.Description, disk.SerialNumber);
            AddToLog("Disk size: {0} ({1:###,###,###,###,##0} sectors, {2} bytes per sector)", UIHelper.GetSizeString(disk.Size), disk.TotalSectors, disk.BytesPerSector);
            if (!(testName == TestName.Read || testName == TestName.Verify))
            {
                bool success = disk.ExclusiveLock();
                if (!success)
                {
                    MessageBox.Show("Failed to lock the disk.");
                    return;
                }

                if (Environment.OSVersion.Version.Major >= 6)
                {
                    success = disk.SetOnlineStatus(false, false);
                    if (!success)
                    {
                        disk.ReleaseLock();
                        MessageBox.Show("Failed to take the disk offline.");
                        return;
                    }
                }
            }

            m_diskTester = new DiskTester(testName, disk);
            m_diskTester.OnStatusUpdate += delegate(long currentPosition)
            {
                UpdateStatus(currentPosition);
            };
            m_diskTester.OnLogUpdate += delegate(string format, object[] args)
            {
                AddToLog(format, args);
            };
            // The last segment might be bigger than the others
            long uiBlockSize = disk.TotalSectors / (HorizontalBlocks * VerticalBlocks);

            m_blocks = new BlockStatus[HorizontalBlocks * VerticalBlocks];
            this.Invoke((MethodInvoker) delegate
            {
                pictureBoxMap.Invalidate();
                pictureBoxMap.Update();
            });
            for (int uiBlockIndex = 0; uiBlockIndex < m_blocks.Length; uiBlockIndex++)
            {
                long sectorIndex = uiBlockIndex * uiBlockSize;
                long sectorCount = uiBlockSize;
                if (uiBlockIndex == m_blocks.Length - 1)
                {
                    sectorCount = disk.TotalSectors - ((m_blocks.Length - 1) * uiBlockSize);
                }
                BlockStatus blockStatus = m_diskTester.PerformTest(sectorIndex, sectorCount);
                m_blocks[uiBlockIndex] = blockStatus;
                this.Invoke((MethodInvoker) delegate
                {
                    pictureBoxMap.Invalidate();
                    pictureBoxMap.Update();
                });
                if (m_diskTester.Abort)
                {
                    break;
                }
            }

            if (testName != TestName.Read)
            {
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    disk.SetOnlineStatus(true, false);
                }
                disk.ReleaseLock();
                disk.UpdateProperties();
            }

            if (m_diskTester.Abort)
            {
                AddToLog("Test Aborted");
            }
            else
            {
                AddToLog("Test Completed");
            }
            m_diskTester = null;
        }
Пример #27
0
 public bool ShouldBeProcessed(PhysicalDisk physicalDisk) =>
 configuration.MonitoringEntries.Any(i => i.PhysicalId.IsChildOfOrEqualTo(physicalDisk.PhysicalId));