public async Task WhenConvertSourceToVhdDestinationThenReadDataIsIdentical() { // arrange var sourcePath = $"{Guid.NewGuid()}.img"; var destinationPath = $"{Guid.NewGuid()}.vhd"; var fakeCommandHelper = new FakeCommandHelper(new [] { sourcePath }, new [] { destinationPath }); var cancellationTokenSource = new CancellationTokenSource(); // act - read source img to destination vhd var convertCommand = new ConvertCommand(new NullLogger <ConvertCommand>(), fakeCommandHelper, sourcePath, destinationPath); var result = await convertCommand.Execute(cancellationTokenSource.Token); Assert.True(result.IsSuccess); // get source bytes var sourceBytes = fakeCommandHelper.GetMedia(sourcePath).GetBytes(); // get destination bytes from vhd var destinationBytes = await ReadMediaBytes(fakeCommandHelper, destinationPath, sourceBytes.Length); var destinationPathSize = new FileInfo(destinationPath).Length; // assert length is not the same (vhd file format different than img) and bytes are the same Assert.NotEqual(sourceBytes.Length, destinationPathSize); Assert.Equal(sourceBytes, destinationBytes); // delete destination path vhd File.Delete(destinationPath); }
public async Task WhenConvertSourceToImgDestinationThenReadDataIsIdentical() { // arrange var sourcePath = $"{Guid.NewGuid()}.img"; var destinationPath = $"{Guid.NewGuid()}.img"; var fakeCommandHelper = new FakeCommandHelper(new [] { sourcePath }, new [] { destinationPath }); var cancellationTokenSource = new CancellationTokenSource(); // act - convert source img to destination img var convertCommand = new ConvertCommand(new NullLogger <ConvertCommand>(), fakeCommandHelper, sourcePath, destinationPath); DataProcessedEventArgs dataProcessedEventArgs = null; convertCommand.DataProcessed += (_, args) => { dataProcessedEventArgs = args; }; var result = await convertCommand.Execute(cancellationTokenSource.Token); Assert.True(result.IsSuccess); Assert.NotNull(dataProcessedEventArgs); Assert.NotEqual(0, dataProcessedEventArgs.PercentComplete); Assert.NotEqual(0, dataProcessedEventArgs.BytesProcessed); Assert.Equal(0, dataProcessedEventArgs.BytesRemaining); Assert.NotEqual(0, dataProcessedEventArgs.BytesTotal); // assert data is identical var sourceBytes = fakeCommandHelper.GetMedia(sourcePath).GetBytes(); var destinationBytes = fakeCommandHelper.GetMedia(destinationPath).GetBytes(); Assert.Equal(sourceBytes, destinationBytes); }
public async ValueTask Handle(IBackgroundTaskContext context) { if (context.BackgroundTask is not ConvertBackgroundTask convertBackgroundTask) { return; } try { var commandHelper = new CommandHelper(); var convertCommand = new ConvertCommand(loggerFactory.CreateLogger <ConvertCommand>(), commandHelper, convertBackgroundTask.SourcePath, convertBackgroundTask.DestinationPath); convertCommand.DataProcessed += async(_, args) => { await progressHubContext.SendProgress(new Progress { Title = convertBackgroundTask.Title, IsComplete = false, PercentComplete = args.PercentComplete, BytesProcessed = args.BytesProcessed, BytesRemaining = args.BytesRemaining, BytesTotal = args.BytesTotal, MillisecondsElapsed = args.PercentComplete > 0 ? (long)args.TimeElapsed.TotalMilliseconds : new long?(), MillisecondsRemaining = args.PercentComplete > 0 ? (long)args.TimeRemaining.TotalMilliseconds : new long?(), MillisecondsTotal = args.PercentComplete > 0 ? (long)args.TimeTotal.TotalMilliseconds : new long?() }, context.Token); }; var result = await convertCommand.Execute(context.Token); await progressHubContext.SendProgress(new Progress { Title = convertBackgroundTask.Title, IsComplete = true, HasError = result.IsFaulted, ErrorMessage = result.IsFaulted ? result.Error.Message : null, PercentComplete = 100 }, context.Token); } catch (Exception e) { await progressHubContext.SendProgress(new Progress { Title = convertBackgroundTask.Title, IsComplete = true, HasError = true, ErrorMessage = e.Message, PercentComplete = 100 }, context.Token); } }
public async Task WhenConvertSourceToImgDestinationWithSizeThenReadDataIsIdentical() { // arrange var sourcePath = $"{Guid.NewGuid()}.img"; var destinationPath = $"{Guid.NewGuid()}.img"; var size = 16 * 512; var fakeCommandHelper = new FakeCommandHelper(new [] { sourcePath }, new [] { destinationPath }); var cancellationTokenSource = new CancellationTokenSource(); // act - convert source img to destination img var convertCommand = new ConvertCommand(new NullLogger <ConvertCommand>(), fakeCommandHelper, sourcePath, destinationPath, size); var result = await convertCommand.Execute(cancellationTokenSource.Token); Assert.True(result.IsSuccess); // assert data is identical within defined size var sourceBytes = fakeCommandHelper.GetMedia(sourcePath).GetBytes(size); Assert.Equal(size, sourceBytes.Length); var destinationBytes = fakeCommandHelper.GetMedia(destinationPath).GetBytes(); Assert.Equal(sourceBytes, destinationBytes); }
public static int Main(string[] args) { CommandLine.Initialize(); var options = new CommandLineParser(args); options.AddOptions(null, OPTIONS_GENERAL); options.AddOptions("help", OPTIONS_HELP); options.AddOptions("version", OPTIONS_VERSION); options.AddOptions("convert", OPTIONS_CONVERT); options.AddOptions("list", OPTIONS_LIST); options.AddOptions("register", OPTIONS_REGISTER); // save the error state bool invalidArguments = !options.Parse("convert"); // get the Quiet option first, before we emit anything Quiet = options.GetOptionSwitch("quiet"); if (Quiet) { Console.SetOut(new StreamWriter(Stream.Null)); Console.SetError(Console.Out); } NoLog = options.GetOptionSwitch("nolog"); if (!NoLog) { Process running_proc = Process.GetCurrentProcess(); Process[] mbinc_procs = Process.GetProcessesByName(running_proc.ProcessName); // If we only have one instance of MBINCompiler running create the usual log. // If a process starts and there is already a running MBINCompiler process, then // add the PID to the log file name so that there is no issue with two processes // attempting to write to the same log file. if (mbinc_procs.Length == 1) { Logger.Open(Path.ChangeExtension(Utils.GetExecutablePath(), ".log")); } else { Logger.Open(Path.ChangeExtension(Utils.GetExecutablePath(), $".{running_proc.Id}.log")); } Logger.EnableTraceLogging = true; Logger.LogMessage("VERSION", $"MBINCompiler v{Version.GetVersionStringCompact()}"); Logger.LogMessage("ARGS", $"\"{string.Join("\" \"", args)}\"\n"); using (var indent = new Logger.IndentScope()) { Logger.LogMessage("If you encounter any errors, please submit a bug report and include this log file.\n" + "Please check that there isn't already a similar issue open before creating a new one.\n" + "https://github.com/monkeyman192/MBINCompiler/issues\n"); } } // now we can emit an error if we need to if (invalidArguments) { return(CommandLine.ShowInvalidCommandLineArg(options)); } // initialize remaining global options DebugMode = options.GetOptionSwitch("debug"); // execute the appropriate mode try { switch (options.Verb) { case "help": return(HelpCommand.Execute(options)); case "version": return(VersionCommand.Execute(options)); case "list": return(ListCommand.Execute(options)); case "register": return(RegisterCommand.Execute(options)); default: return(ConvertCommand.Execute(options)); } } catch (System.Exception e) { return(CommandLine.ShowException(e)); } }
static async Task Run(Arguments arguments) { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); var serviceProvider = new ServiceCollection() .AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true)) .BuildServiceProvider(); var loggerFactory = serviceProvider.GetService <ILoggerFactory>(); var isAdministrator = OperatingSystem.IsAdministrator(); if (!isAdministrator) { Console.WriteLine("Requires administrator rights!"); } var commandHelper = new CommandHelper(); var physicalDrives = (await GetPhysicalDrives(arguments)).ToList(); var cancellationTokenSource = new CancellationTokenSource(); switch (arguments.Command) { case Arguments.CommandEnum.List: var listCommand = new ListCommand(loggerFactory.CreateLogger <ListCommand>(), commandHelper, physicalDrives); listCommand.ListRead += (_, args) => { // // await Task.Run(() => // { // Console.WriteLine(JsonSerializer.Serialize(physicalDrivesList, JsonSerializerOptions)); // }); InfoPresenter.PresentInfo(args.MediaInfos); }; var listResult = await listCommand.Execute(cancellationTokenSource.Token); Console.WriteLine(listResult.IsSuccess ? "Done" : $"ERROR: Read failed, {listResult.Error}"); break; case Arguments.CommandEnum.Info: var infoCommand = new InfoCommand(loggerFactory.CreateLogger <InfoCommand>(), commandHelper, physicalDrives, arguments.SourcePath); infoCommand.DiskInfoRead += (_, args) => { InfoPresenter.PresentInfo(args.MediaInfo); }; var infoResult = await infoCommand.Execute(cancellationTokenSource.Token); Console.WriteLine(infoResult.IsSuccess ? "Done" : $"ERROR: Read failed, {infoResult.Error}"); break; case Arguments.CommandEnum.Read: Console.WriteLine("Reading physical drive to image file"); GenericPresenter.PresentPaths(arguments); var readCommand = new ReadCommand(loggerFactory.CreateLogger <ReadCommand>(), commandHelper, physicalDrives, arguments.SourcePath, arguments.DestinationPath, arguments.Size); readCommand.DataProcessed += (_, args) => { GenericPresenter.Present(args); }; var readResult = await readCommand.Execute(cancellationTokenSource.Token); Console.WriteLine(readResult.IsSuccess ? "Done" : $"ERROR: Read failed, {readResult.Error}"); break; case Arguments.CommandEnum.Convert: Console.WriteLine("Converting source image to destination image file"); GenericPresenter.PresentPaths(arguments); var convertCommand = new ConvertCommand(loggerFactory.CreateLogger <ConvertCommand>(), commandHelper, arguments.SourcePath, arguments.DestinationPath, arguments.Size); convertCommand.DataProcessed += (_, args) => { GenericPresenter.Present(args); }; var convertResult = await convertCommand.Execute(cancellationTokenSource.Token); Console.WriteLine( convertResult.IsSuccess ? "Done" : $"ERROR: Convert failed, {convertResult.Error}"); break; case Arguments.CommandEnum.Write: Console.WriteLine("Writing source image file to physical drive"); GenericPresenter.PresentPaths(arguments); var writeCommand = new WriteCommand(loggerFactory.CreateLogger <WriteCommand>(), commandHelper, physicalDrives, arguments.SourcePath, arguments.DestinationPath, arguments.Size); writeCommand.DataProcessed += (_, args) => { GenericPresenter.Present(args); }; var writeResult = await writeCommand.Execute(cancellationTokenSource.Token); Console.WriteLine(writeResult.IsSuccess ? "Done" : $"ERROR: Write failed, {writeResult.Error}"); break; case Arguments.CommandEnum.Verify: Console.WriteLine("Verifying source image to destination"); GenericPresenter.PresentPaths(arguments); var verifyCommand = new VerifyCommand(loggerFactory.CreateLogger <VerifyCommand>(), commandHelper, physicalDrives, arguments.SourcePath, arguments.DestinationPath, arguments.Size); verifyCommand.DataProcessed += (_, args) => { GenericPresenter.Present(args); }; var verifyResult = await verifyCommand.Execute(cancellationTokenSource.Token); Console.WriteLine(verifyResult.IsSuccess ? "Done" : $"ERROR: Verify failed, {verifyResult.Error}"); break; case Arguments.CommandEnum.Blank: Console.WriteLine("Creating blank image"); Console.WriteLine($"Path: {arguments.SourcePath}"); var blankCommand = new BlankCommand(loggerFactory.CreateLogger <BlankCommand>(), commandHelper, arguments.SourcePath, arguments.Size); var blankResult = await blankCommand.Execute(cancellationTokenSource.Token); Console.WriteLine(blankResult.IsSuccess ? "Done" : $"ERROR: Blank failed, {blankResult.Error}"); break; case Arguments.CommandEnum.Optimize: Console.WriteLine("Optimizing image file"); Console.WriteLine($"Path: {arguments.SourcePath}"); var optimizeCommand = new OptimizeCommand(loggerFactory.CreateLogger <OptimizeCommand>(), commandHelper, arguments.SourcePath); var optimizeResult = await optimizeCommand.Execute(cancellationTokenSource.Token); Console.WriteLine(optimizeResult.IsSuccess ? "Done" : $"ERROR: Optimize failed, {optimizeResult.Error}"); break; } }