public override void ExecuteCmdlet() { IEnumerable <VirtualHardDisk> results = null; var virtualHardDiskOperations = new VirtualHardDiskOperations(this.WebClientFactory); if (this.ParameterSetName == WAPackCmdletParameterSets.Empty) { results = virtualHardDiskOperations.Read(); } else if (this.ParameterSetName == WAPackCmdletParameterSets.FromId) { VirtualHardDisk virtualHardDisk = null; virtualHardDisk = virtualHardDiskOperations.Read(ID); results = new List <VirtualHardDisk>() { virtualHardDisk }; } else if (this.ParameterSetName == WAPackCmdletParameterSets.FromName) { results = virtualHardDiskOperations.Read(new Dictionary <string, string>() { { "Name", Name } }); } this.GenerateCmdletOutput(results); }
public static void Test(string path, long size) { int bytesPerCluster = 512; while (bytesPerCluster <= 65536) { string volumeLabel = "FormatTest_" + bytesPerCluster.ToString(); VirtualHardDisk disk = VirtualHardDisk.CreateFixedDisk(path, size); disk.ExclusiveLock(); Partition partition = CreatePrimaryPartition(disk); NTFSVolumeCreator.Format(partition, bytesPerCluster, volumeLabel); disk.ReleaseLock(); VHDMountHelper.MountVHD(path); string driveName = MountHelper.WaitForDriveToMount(volumeLabel); if (driveName == null) { throw new Exception("Timeout waiting for volume to mount"); } bool isErrorFree = ChkdskHelper.Chkdsk(driveName); if (!isErrorFree) { throw new InvalidDataException("CHKDSK reported errors"); } VHDMountHelper.UnmountVHD(path); File.Delete(path); bytesPerCluster = bytesPerCluster * 2; } }
public static void CreateVDisk(KeyValuePairList <string, string> parameters) { if (!VerifyParameters(parameters, "file", "size")) { Console.WriteLine(); Console.WriteLine("Invalid parameter."); HelpCreate(); return; } long sizeInBytes; if (parameters.ContainsKey("size")) { long requestedSizeInMB = Conversion.ToInt64(parameters.ValueOf("size"), 0); sizeInBytes = requestedSizeInMB * 1024 * 1024; if (requestedSizeInMB <= 0) { Console.WriteLine("Invalid size (must be specified in MB)."); return; } } else { Console.WriteLine("The SIZE parameter must be specified."); return; } if (parameters.ContainsKey("file")) { string path = parameters.ValueOf("file"); if (new FileInfo(path).Exists) { Console.WriteLine("Error: file already exists."); return; } try { m_selectedDisk = VirtualHardDisk.Create(path, sizeInBytes); Console.WriteLine("The virtual disk file was created successfully."); } catch (IOException) { Console.WriteLine("Error: Could not write the virtual disk file."); return; } catch (UnauthorizedAccessException) { Console.WriteLine("Error: Access Denied, Could not write the virtual disk file."); return; } } else { Console.WriteLine("The FILE parameter was not specified."); } }
private static void CreateProvider(GeeksCloud geeksCloud) { var virtualHardDisk = new VirtualHardDisk(); var vm = new Vm("VirtualMachine", virtualHardDisk); var uatInfrastructure = new UatInfrastructure(); geeksCloud.CreateResource(vm, uatInfrastructure); }
//AddDataDisk //DeleteDataDisk //GetDataDisk //UpdateDataDisk public Task<string> CreateDiskAsync(string name, string label, Uri linkToBlob, OperatingSystemType osType = OperatingSystemType.None, CancellationToken token = default(CancellationToken)) { VirtualHardDisk info = new VirtualHardDisk(name, label, linkToBlob, osType); HttpRequestMessage message = CreateBaseMessage(HttpMethod.Post, CreateTargetUri(UriFormatStrings.Disks), info); return StartSendTask(message, token); }
private static VirtualHardDisk PsObjectToVhdObject(PSObject psObject) { var vhd = new VirtualHardDisk { Path = (string)psObject.Properties["Path"].Value, DiskNumber = (uint)(psObject.Properties["Number"].Value ?? 0u) }; return(vhd); }
public void SetDiskGeometry(ulong totalSectors) { byte heads; byte sectorsPerTrack; ushort cylinders; VirtualHardDisk.GetDiskGeometry(totalSectors, out heads, out sectorsPerTrack, out cylinders); DiskGeometry = (uint)cylinders << 16; DiskGeometry |= (uint)heads << 8; DiskGeometry |= sectorsPerTrack; }
private static void TestCreateAndDeleteFiles(string path, long size, int count) { int bytesPerCluster = 512; while (bytesPerCluster <= 65536) { string volumeLabel = "CreateFilesTest_" + bytesPerCluster.ToString(); VirtualHardDisk disk = VirtualHardDisk.CreateFixedDisk(path, size); disk.ExclusiveLock(); Partition partition = NTFSFormatTests.CreatePrimaryPartition(disk); NTFSVolume volume = NTFSVolumeCreator.Format(partition, bytesPerCluster, volumeLabel); string directoryName = "Directory"; CreateFiles(volume, directoryName, count); disk.ReleaseLock(); VHDMountHelper.MountVHD(path); string driveName = MountHelper.WaitForDriveToMount(volumeLabel); if (driveName == null) { throw new Exception("Timeout waiting for volume to mount"); } bool isErrorFree = ChkdskHelper.Chkdsk(driveName); if (!isErrorFree) { throw new InvalidDataException("CHKDSK reported errors"); } if (count != Directory.GetFiles(driveName + directoryName).Length) { throw new InvalidDataException("Test failed"); } VHDMountHelper.UnmountVHD(path); disk.ExclusiveLock(); volume = new NTFSVolume(partition); DeleteFiles(volume, directoryName, count); disk.ReleaseLock(); VHDMountHelper.MountVHD(path); isErrorFree = ChkdskHelper.Chkdsk(driveName); if (!isErrorFree) { throw new InvalidDataException("CHKDSK reported errors"); } if (Directory.GetFiles(driveName + directoryName).Length > 0) { throw new InvalidDataException("Test failed"); } VHDMountHelper.UnmountVHD(path); File.Delete(path); bytesPerCluster = bytesPerCluster * 2; } }
internal OSDisk(OperatingSystemTypes?osType, DiskEncryptionSettings encryptionSettings, string name, VirtualHardDisk vhd, VirtualHardDisk image, CachingTypes?caching, bool?writeAcceleratorEnabled, DiffDiskSettings diffDiskSettings, DiskCreateOptionTypes createOption, int?diskSizeGB, ManagedDiskParameters managedDisk) { OsType = osType; EncryptionSettings = encryptionSettings; Name = name; Vhd = vhd; Image = image; Caching = caching; WriteAcceleratorEnabled = writeAcceleratorEnabled; DiffDiskSettings = diffDiskSettings; CreateOption = createOption; DiskSizeGB = diskSizeGB; ManagedDisk = managedDisk; }
internal DataDisk(int lun, string name, VirtualHardDisk vhd, VirtualHardDisk image, CachingTypes?caching, bool?writeAcceleratorEnabled, DiskCreateOptionTypes createOption, int?diskSizeGB, ManagedDiskParameters managedDisk, bool?toBeDetached, long?diskIopsReadWrite, long?diskMBpsReadWrite) { Lun = lun; Name = name; Vhd = vhd; Image = image; Caching = caching; WriteAcceleratorEnabled = writeAcceleratorEnabled; CreateOption = createOption; DiskSizeGB = diskSizeGB; ManagedDisk = managedDisk; ToBeDetached = toBeDetached; DiskIopsReadWrite = diskIopsReadWrite; DiskMBpsReadWrite = diskMBpsReadWrite; }
private static void TestMove(string path, long size) { int bytesPerCluster = 512; while (bytesPerCluster <= 65536) { string volumeLabel = "MoveTest_" + bytesPerCluster.ToString(); VirtualHardDisk disk = VirtualHardDisk.CreateFixedDisk(path, size); disk.ExclusiveLock(); Partition partition = NTFSFormatTests.CreatePrimaryPartition(disk); NTFSVolume volume = NTFSVolumeCreator.Format(partition, bytesPerCluster, volumeLabel); string directory1Name = "Directory1"; string directory2Name = "Directory2"; FileRecord directory1Record = volume.CreateFile(NTFSVolume.RootDirSegmentReference, directory1Name, true); FileRecord directory2Record = volume.CreateFile(NTFSVolume.RootDirSegmentReference, directory2Name, true); string fileNameBefore = "Test1.txt"; string fileNameAfter = "Test2.txt"; FileRecord fileRecord = volume.CreateFile(directory1Record.BaseSegmentReference, fileNameBefore, false); NTFSFile file = new NTFSFile(volume, fileRecord); byte[] fileData = System.Text.Encoding.ASCII.GetBytes("Test"); file.Data.WriteBytes(0, fileData); volume.UpdateFileRecord(fileRecord); volume.MoveFile(fileRecord, directory2Record.BaseSegmentReference, fileNameAfter); disk.ReleaseLock(); VHDMountHelper.MountVHD(path); string driveName = MountHelper.WaitForDriveToMount(volumeLabel); if (driveName == null) { throw new Exception("Timeout waiting for volume to mount"); } bool isErrorFree = ChkdskHelper.Chkdsk(driveName); if (!isErrorFree) { throw new InvalidDataException("CHKDSK reported errors"); } byte[] bytesRead = File.ReadAllBytes(driveName + directory2Name + "\\" + fileNameAfter); if (!ByteUtils.AreByteArraysEqual(fileData, bytesRead)) { throw new InvalidDataException("Test failed"); } VHDMountHelper.UnmountVHD(path); File.Delete(path); bytesPerCluster = bytesPerCluster * 2; } }
public static void CreateVolumeWithPendingFileCreation(string path, long size, int bytesPerCluster, string volumeLabel, string fileName, byte[] fileData) { VirtualHardDisk disk = VirtualHardDisk.CreateFixedDisk(path, size); disk.ExclusiveLock(); Partition partition = NTFSFormatTests.CreatePrimaryPartition(disk); NTFSVolume volume = NTFSVolumeCreator.Format(partition, bytesPerCluster, volumeLabel); long segmentNumber = MasterFileTable.FirstUserSegmentNumber; FileNameRecord fileNameRecord = new FileNameRecord(MasterFileTable.RootDirSegmentReference, fileName, false, DateTime.Now); FileRecordSegment fileRecordSegment = CreateFileRecordSegment(segmentNumber, fileNameRecord, fileData); ulong dataStreamOffset = (ulong)(segmentNumber * volume.BytesPerFileRecordSegment); byte[] redoData = fileRecordSegment.GetBytes(volume.BytesPerFileRecordSegment, volume.MinorVersion, false); MftSegmentReference mftFileReference = new MftSegmentReference(0, 1); AttributeRecord mftDataRecord = volume.GetFileRecord(mftFileReference).GetAttributeRecord(AttributeType.Data, String.Empty); AttributeRecord mftBitmapRecord = volume.GetFileRecord(mftFileReference).GetAttributeRecord(AttributeType.Bitmap, String.Empty); uint transactionID = volume.LogClient.AllocateTransactionID(); volume.LogClient.WriteLogRecord(mftFileReference, mftDataRecord, dataStreamOffset, volume.BytesPerFileRecordSegment, NTFSLogOperation.InitializeFileRecordSegment, redoData, NTFSLogOperation.Noop, new byte[0], transactionID); long bitmapVCN = segmentNumber / (volume.BytesPerCluster * 8); int bitOffsetInCluster = (int)(segmentNumber % (volume.BytesPerCluster * 8)); BitmapRange bitmapRange = new BitmapRange((uint)bitOffsetInCluster, 1); ulong bitmapStreamOffset = (ulong)(bitmapVCN * volume.BytesPerCluster); volume.LogClient.WriteLogRecord(mftFileReference, mftBitmapRecord, bitmapStreamOffset, volume.BytesPerCluster, NTFSLogOperation.SetBitsInNonResidentBitMap, bitmapRange.GetBytes(), NTFSLogOperation.Noop, new byte[0], transactionID); FileRecord parentDirectoryRecord = volume.GetFileRecord(MasterFileTable.RootDirSegmentReference); IndexData parentDirectoryIndex = new IndexData(volume, parentDirectoryRecord, AttributeType.FileName); byte[] fileNameRecordBytes = fileNameRecord.GetBytes(); long leafRecordVBN = 0; IndexRecord leafRecord = parentDirectoryIndex.ReadIndexRecord(leafRecordVBN); ulong indexAllocationOffset = (ulong)parentDirectoryIndex.ConvertToDataOffset(leafRecordVBN); int insertIndex = CollationHelper.FindIndexForSortedInsert(leafRecord.IndexEntries, fileNameRecordBytes, CollationRule.Filename); int insertOffset = leafRecord.GetEntryOffset(volume.BytesPerIndexRecord, insertIndex); AttributeRecord rootDirIndexAllocation = volume.GetFileRecord(MasterFileTable.RootDirSegmentReference).GetAttributeRecord(AttributeType.IndexAllocation, IndexHelper.GetIndexName(AttributeType.FileName)); IndexEntry indexEntry = new IndexEntry(fileRecordSegment.SegmentReference, fileNameRecord.GetBytes()); volume.LogClient.WriteLogRecord(MasterFileTable.RootDirSegmentReference, rootDirIndexAllocation, indexAllocationOffset, volume.BytesPerIndexRecord, 0, insertOffset, NTFSLogOperation.AddIndexEntryToAllocationBuffer, indexEntry.GetBytes(), NTFSLogOperation.Noop, new byte[0], transactionID, false); volume.LogClient.WriteForgetTransactionRecord(transactionID, true); disk.ReleaseLock(); }
internal AzureSLA GetDiskSLA(int?diskSize, VirtualHardDisk vhd) { if (!diskSize.HasValue && vhd != null) { diskSize = this.GetDiskSizeGbFromBlobUri(vhd.Uri); } if (!diskSize.HasValue) { this.WriteWarning("OS Disk size is empty and could not be determined. Assuming P10."); diskSize = 127; } AzureSLA sla = new AzureSLA(); if (diskSize > 0 && diskSize < 129) { // P10 sla.IOPS = 500; sla.TP = 100; } else if (diskSize > 0 && diskSize < 513) { // P20 sla.IOPS = 2300; sla.TP = 150; } else if (diskSize > 0 && diskSize < 1024) { // P30 sla.IOPS = 5000; sla.TP = 200; } else { WriteError("Unkown disk size for Premium Storage - {0}", diskSize); throw new ArgumentException("Unkown disk size for Premium Storage"); } return(sla); }
private void UpdateDiskDetails(IList<DiskDetails> diskDetails) { this.Disks = new List<VirtualHardDisk>(); foreach (var disk in diskDetails) { VirtualHardDisk hd = new VirtualHardDisk(); hd.Id = disk.VhdId; hd.Name = disk.VhdName; this.Disks.Add(hd); } DiskDetails OSDisk = diskDetails.SingleOrDefault(d => string.Compare(d.VhdType, "OperatingSystem", StringComparison.OrdinalIgnoreCase) == 0); if (OSDisk != null) { this.OSDiskId = OSDisk.VhdId; this.OSDiskName = OSDisk.VhdName; } }
private void btnOK_Click(object sender, EventArgs e) { string path = txtFilePath.Text; long size = (long)numericDiskSize.Value * 1024 * 1024; if (path == String.Empty) { MessageBox.Show("Please choose file location", "Error"); return; } m_isWorking = true; new Thread(delegate() { DiskImage diskImage; try { diskImage = VirtualHardDisk.CreateFixedDisk(path, size); } catch (IOException ex) { this.Invoke((MethodInvoker) delegate() { MessageBox.Show("Failed to create the disk: " + ex.Message, "Error"); txtFilePath.Enabled = true; btnBrowse.Enabled = true; numericDiskSize.Enabled = true; btnOK.Enabled = true; btnCancel.Enabled = true; }); m_isWorking = false; return; } bool isLocked = diskImage.ExclusiveLock(); if (!isLocked) { this.Invoke((MethodInvoker) delegate() { MessageBox.Show("Cannot lock the disk image for exclusive access", "Error"); txtFilePath.Enabled = true; btnBrowse.Enabled = true; numericDiskSize.Enabled = true; btnOK.Enabled = true; btnCancel.Enabled = true; }); m_isWorking = false; return; } m_diskImage = diskImage; m_isWorking = false; this.Invoke((MethodInvoker) delegate() { this.DialogResult = DialogResult.OK; this.Close(); }); }).Start(); txtFilePath.Enabled = false; btnBrowse.Enabled = false; numericDiskSize.Enabled = false; btnOK.Enabled = false; btnCancel.Enabled = false; }
private void UpdateDiskDetails(AzureVmDiskDetails diskDetails) { this.Disks = new List<VirtualHardDisk>(); foreach (var disk in diskDetails.Disks) { VirtualHardDisk hd = new VirtualHardDisk(); hd.Id = disk.Id; hd.Name = disk.Name; this.Disks.Add(hd); } this.OSDiskId = diskDetails.VHDId; this.OSDiskName = diskDetails.OsDisk; this.OS = diskDetails.OsType; }
internal AzureSLA GetDiskSLA(int?diskSize, VirtualHardDisk vhd) { if (!diskSize.HasValue && vhd != null) { diskSize = this.GetDiskSizeGbFromBlobUri(vhd.Uri); } if (!diskSize.HasValue) { this.WriteWarning("OS Disk size is empty and could not be determined. Assuming P10."); diskSize = 127; } AzureSLA sla = new AzureSLA(); if (diskSize > 0 && diskSize <= 32) { // P4 sla.IOPS = 120; sla.TP = 125; } else if (diskSize > 0 && diskSize <= 64) { // P6 sla.IOPS = 240; sla.TP = 50; } else if (diskSize > 0 && diskSize <= 128) { // P10 sla.IOPS = 500; sla.TP = 100; } else if (diskSize > 0 && diskSize <= 512) { // P20 sla.IOPS = 2300; sla.TP = 150; } else if (diskSize > 0 && diskSize <= 1024) { // P30 sla.IOPS = 5000; sla.TP = 200; } else if (diskSize > 0 && diskSize <= 2048) { // P40 sla.IOPS = 7500; sla.TP = 250; } else if (diskSize > 0 && diskSize <= (4 * 1024)) { // P50 sla.IOPS = 7500; sla.TP = 250; } else if (diskSize > 0 && diskSize <= (8 * 1024)) { // P60 sla.IOPS = 12500; sla.TP = 480; } else if (diskSize > 0 && diskSize <= (16 * 1024)) { // P70 sla.IOPS = 15000; sla.TP = 750; } else if (diskSize > 0 && diskSize <= (32 * 1024)) { // P80 sla.IOPS = 20000; sla.TP = 750; } else { WriteError("Unkown disk size for Premium Storage - {0}", diskSize); throw new ArgumentException("Unkown disk size for Premium Storage"); } return(sla); }
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(); } }
private void MainForm_Load(object sender, EventArgs e) { Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; this.Text += " v" + version.ToString(3); m_server.OnLogEntry += Program.OnLogEntry; List <IPAddress> localIPs = GetHostIPAddresses(); KeyValuePairList <string, IPAddress> list = new KeyValuePairList <string, IPAddress>(); list.Add("Any", IPAddress.Any); foreach (IPAddress address in localIPs) { list.Add(address.ToString(), address); } comboIPAddress.DataSource = list; comboIPAddress.DisplayMember = "Key"; comboIPAddress.ValueMember = "Value"; lblStatus.Text = "Author: Tal Aloni ([email protected])"; #if Win32 if (!SecurityHelper.IsAdministrator()) { lblStatus.Text = "Some features require administrator privileges and have been disabled"; } #endif //test string[] args = Environment.GetCommandLineArgs(); if (args.Length > 1) { //to do /* * if (args[0].Equals("DiskImage", StringComparison.OrdinalIgnoreCase)) { m_disks.Add(DiskImage.GetDiskImage(args[2], false)); } */ } if (System.IO.File.Exists("config.xml") && args.Length <= 1) { XmlDocument XmlDocObj = new XmlDocument(); XmlDocObj.Load("config.xml"); XmlNode node = XmlDocObj.SelectSingleNode("//target"); string targetname = ""; string targetpath = ""; string targettype = ""; string targetsize = ""; string targetdiskindex = ""; if (node.Attributes["name"] != null) { targetname = node.Attributes["name"].Value; } if (node.Attributes["path"] != null) { targetpath = node.Attributes["path"].Value; } if (node.Attributes["class"] != null) { targettype = node.Attributes["class"].Value; } if (node.Attributes["size"] != null) { targetsize = node.Attributes["size"].Value; } if (node.Attributes["index"] != null) { targetdiskindex = node.Attributes["index"].Value; } if (targetname != "") { // List <Disk> m_disks = new List <Disk>(); if (targettype.Equals("RAMDisk", StringComparison.OrdinalIgnoreCase)) { m_disks.Add(new RAMDisk(int.Parse(targetsize) * 1024 * 1024)); } if (targettype.Equals("DiskImage", StringComparison.OrdinalIgnoreCase)) { m_disks.Add(DiskImage.GetDiskImage(targetpath, false)); } if (targettype.Equals("createDiskImage", StringComparison.OrdinalIgnoreCase)) { m_disks.Add(VirtualHardDisk.CreateFixedDisk(targetpath, long.Parse(targetsize) * 1024 * 1024)); } if (targettype.Equals("createRawDiskImage", StringComparison.OrdinalIgnoreCase)) { m_disks.Add(RawDiskImage.Create(targetpath, long.Parse(targetsize) * 1024 * 1024)); } if (targettype.Equals("PhysicalDisk", StringComparison.OrdinalIgnoreCase)) { m_disks.Add(new PhysicalDisk(int.Parse(targetdiskindex))); } ISCSITarget target = new ISCSITarget(targetname, m_disks); ((SCSI.VirtualSCSITarget)target.SCSITarget).OnLogEntry += Program.OnLogEntry; target.OnAuthorizationRequest += new EventHandler <AuthorizationRequestArgs>(ISCSITarget_OnAuthorizationRequest); target.OnSessionTermination += new EventHandler <SessionTerminationArgs>(ISCSITarget_OnSessionTermination); m_targets.Add(target); // try { m_server.AddTarget(target); } catch (ArgumentException ex) { MessageBox.Show(ex.Message, "Error"); return; } listTargets.Items.Add(target.TargetName); } } }
static void Main(string[] args) { Console.WriteLine("ConvertIsoToVhdx - Copyright (C) 2017-" + DateTime.Now.Year + " Simon Mourier. All rights reserved."); Console.WriteLine(); if (CommandLine.HelpRequested || args.Length < 2) { Help(); return; } inputFilePath = CommandLine.GetNullifiedArgument(0); outputFilePath = CommandLine.GetNullifiedArgument(1); if (inputFilePath == null || outputFilePath == null) { Help(); return; } inputFilePath = Path.GetFullPath(inputFilePath); outputFilePath = Path.GetFullPath(outputFilePath); Console.WriteLine("Input file: " + inputFilePath); Console.WriteLine("Output file: " + outputFilePath); _logFilePath = CommandLine.GetNullifiedArgument("log"); int systemPartitionSizeInMB = Math.Max(CommandLine.GetArgument("systemPartitionSizeInMB", 0), 100); if (_logFilePath != null) { _logFilePath = Path.GetFullPath(_logFilePath); WimFile.RegisterLogfile(_logFilePath); Console.WriteLine("Logging Imaging information to log file: " + _logFilePath); } Console.WriteLine(); Console.CancelKeyPress += OnConsoleCancelKeyPress; _iso = ManagementExtensions.MountDiskImage(inputFilePath, out var driveLetter); Console.WriteLine(inputFilePath + " has been mounted as drive '" + driveLetter + "'."); try { var input = driveLetter + @":\sources\install.wim"; if (!File.Exists(input)) { Console.WriteLine("Error: windows image file at '" + input + "' was not found."); return; } var options = new WimFileOpenOptions(); options.RegisterForEvents = true; Console.WriteLine("Opening windows image file '" + input + "'."); using (var file = new WimFile(input, options)) { if (file.ImagesCount == 0) { Console.WriteLine("Error: windows image file at '" + input + "' does not contain any image."); return; } file.Event += OnFileEvent; var diskSize = 512 * (file.Images[0].Size / 512); Console.WriteLine("Creating virtual disk '" + outputFilePath + "'. Maximum size: " + diskSize + " (" + Conversions.FormatByteSize(diskSize) + ")"); using (var vdisk = VirtualHardDisk.CreateDisk(outputFilePath, diskSize, IntPtr.Zero, true)) { vdisk.Attach(); var disk = ManagementExtensions.GetDisk(vdisk.DiskIndex); Console.WriteLine("Virtual disk path: " + disk["Path"]); var size = (ulong)disk["Size"]; Console.WriteLine("Virtual disk size: " + size + " bytes (" + Conversions.FormatByteSize(size) + ")"); //disk.Dump(); var result = disk.InvokeMethod("Initialize", new Dictionary <string, object> { { "PartitionStyle", 2 } // GPT }); // reread the disk disk = ManagementExtensions.GetDisk(vdisk.DiskIndex); Console.WriteLine("Virtual disk partition style: " + disk["PartitionStyle"]); //disk.Dump(); //var PARTITION_SYSTEM_GUID = "{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}"; //// https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/configure-uefigpt-based-hard-drive-partitions //result = disk.InvokeMethod("CreatePartition", new Dictionary<string, object> // { // { "Size", systemPartitionSizeInMB * 1024 * 1024L }, // { "GptType", PARTITION_SYSTEM_GUID } // }); //var systemPartition = (ManagementBaseObject)result["CreatedPartition"]; //Console.WriteLine("System partition GPT Type: " + systemPartition["GptType"]); ////systemPartition.Dump(); //var systemVolume = ManagementExtensions.GetPartitionVolume(systemPartition); //systemVolume.InvokeMethod("Format", new Dictionary<string, object> // { // { "FileSystem", "FAT32" }, // //{ "Force", true }, // //{ "Full", false }, // { "Compress", true } // }); //// reread the disk //disk = ManagementExtensions.GetDisk(vdisk.DiskIndex); ////disk.Dump(); var PARTITION_BASIC_DATA_GUID = "{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}"; result = disk.InvokeMethod("CreatePartition", new Dictionary <string, object> { { "UseMaximumSize", true }, //{ "AssignDriveLetter", true }, { "GptType", PARTITION_BASIC_DATA_GUID } }); var partition = (ManagementBaseObject)result["CreatedPartition"]; //partition.Dump(); Console.WriteLine("Data partition GPT Type: " + partition["GptType"]); var volume = ManagementExtensions.GetPartitionVolume(partition); volume.InvokeMethod("Format", new Dictionary <string, object> { { "FileSystem", "NTFS" }, { "Compress", true } //{ "Force", true }, //{ "Full", false } }); //volume.Dump(); Console.WriteLine("Data volume path: " + volume["Path"]); Console.WriteLine("Applying..."); Console.WriteLine(); Console.WriteLine("Completed 00%"); int col = 10; int fixedLines = 1; _percentLeft = col; _percentTop = Console.CursorTop - fixedLines; Console.CursorVisible = false; file.Images[0].Apply((string)volume["Path"]); } } } finally { Console.CursorVisible = true; Console.WriteLine(); ManagementExtensions.UnmountDiskImage(_iso); Console.WriteLine(inputFilePath + " has been unmounted."); } }
public static VirtualHardDisk CreateVirtualHardDisk(global::System.Guid ID, global::System.Guid stampId, global::System.Collections.ObjectModel.ObservableCollection<string> tag) { VirtualHardDisk virtualHardDisk = new VirtualHardDisk(); virtualHardDisk.ID = ID; virtualHardDisk.StampId = stampId; if ((tag == null)) { throw new global::System.ArgumentNullException("tag"); } virtualHardDisk.Tag = tag; return virtualHardDisk; }