public async Task WhenWriteSourceToImgDestinationThenReadDataIsIdentical()
        {
            // arrange
            var sourcePath              = $"{Guid.NewGuid()}.img";
            var destinationPath         = $"{Guid.NewGuid()}.img";
            var fakeCommandHelper       = new FakeCommandHelper(new[] { sourcePath }, new [] { destinationPath });
            var cancellationTokenSource = new CancellationTokenSource();

            // act - write source img to destination img
            var writeCommand =
                new WriteCommand(new NullLogger <WriteCommand>(), fakeCommandHelper, new List <IPhysicalDrive>(), sourcePath, destinationPath);
            DataProcessedEventArgs dataProcessedEventArgs = null;

            writeCommand.DataProcessed += (_, args) =>
            {
                dataProcessedEventArgs = args;
            };
            var result = await writeCommand.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 WriteBackgroundTask writeBackgroundTask)
            {
                return;
            }

            try
            {
                var physicalDrives = await physicalDriveManager.GetPhysicalDrives();

                var commandHelper = new CommandHelper();
                var writeCommand  =
                    new WriteCommand(loggerFactory.CreateLogger <WriteCommand>(), commandHelper, physicalDrives, writeBackgroundTask.SourcePath,
                                     writeBackgroundTask.DestinationPath);
                writeCommand.DataProcessed += async(_, args) =>
                {
                    await progressHubConnection.UpdateProgress(new Progress
                    {
                        Title               = writeBackgroundTask.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 writeCommand.Execute(context.Token);

                await progressHubConnection.UpdateProgress(new Progress
                {
                    Title           = writeBackgroundTask.Title,
                    IsComplete      = true,
                    HasError        = result.IsFaulted,
                    ErrorMessage    = result.IsFaulted ? result.Error.Message : null,
                    PercentComplete = 100
                }, context.Token);
            }
            catch (Exception e)
            {
                await progressHubConnection.UpdateProgress(new Progress
                {
                    Title           = writeBackgroundTask.Title,
                    IsComplete      = true,
                    HasError        = true,
                    ErrorMessage    = e.Message,
                    PercentComplete = 100
                }, context.Token);
            }
        }
Beispiel #3
0
        private void AddJobBtn_Click(object sender, EventArgs e)
        {
            if (DescriptionTxtbox.Text == "")
            {
                DesManLbl.Visible = true;
            }

            if (TitleTxtbox.Text == "")
            {
                TitManLbl.Visible = true;
            }

            if (CompanyTxtbox.Text == "")
            {
                ComManLbl.Visible = true;
            }
            if (CompanyTxtbox.Text == "")
            {
                LocManLbl.Visible = true;
            }
            else
            {
                string stream_id   = (StreamComBox.SelectedIndex + 1).ToString();
                string status_id   = (StatusComBox.SelectedIndex + 1).ToString();
                string description = DescriptionTxtbox.Text;
                string title       = TitleTxtbox.Text;
                string deadline    = DeadlinedatePicker1.Value.ToString();
                string company     = CompanyTxtbox.Text;
                string location    = LocTxtbox.Text;
                DesManLbl.Visible = false;
                TitManLbl.Visible = false;
                ComManLbl.Visible = false;
                LocManLbl.Visible = false;
                string addJobQry = "INSERT INTO JobPost (Job_id, User_id, Stream_id, Status_id, Description, " +
                                   "Title, DatePosted, Deadline, Company, Location) VALUES (job_id_seq.nextval, 6, " +
                                   stream_id + ", " +
                                   status_id + ", " +
                                   description + ", " +
                                   title +
                                   ", SYSDATE, " +
                                   deadline +
                                   ", " + company + ", " +
                                   location;
                IWriteCommand cmd = new WriteCommand();
                if (cmd.Execute(addJobQry))
                {
                    DescriptionTxtbox.Text = "";
                    TitleTxtbox.Text       = "";
                    CompanyTxtbox.Text     = "";
                    CompanyTxtbox.Text     = "";
                }
                else
                {
                    JobMsgLbl.Text      = "Adding Job Failed.";
                    JobMsgLbl.ForeColor = Color.Red;
                }
                JobMsgLbl.Visible = true;
            }
        }
        public async Task WhenWriteSourceToVhdDestinationThenReadDataIsIdentical()
        {
            // arrange
            var sourcePath              = $"{Guid.NewGuid()}.img";
            var destinationPath         = $"{Guid.NewGuid()}.vhd";
            var fakeCommandHelper       = new FakeCommandHelper(new[] { sourcePath });
            var cancellationTokenSource = new CancellationTokenSource();

            // arrange destination vhd has copy of source img data
            var sourceBytes = fakeCommandHelper.GetMedia(sourcePath).GetBytes();

            // act - write source img to destination vhd
            var writeCommand = new WriteCommand(new NullLogger <WriteCommand>(), fakeCommandHelper, new List <IPhysicalDrive>(), sourcePath, destinationPath, sourceBytes.Length);
            var result       = await writeCommand.Execute(cancellationTokenSource.Token);

            Assert.True(result.IsSuccess);

            // delete destination path vhd
            File.Delete(destinationPath);
        }
Beispiel #5
0
        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;
            }
        }