Example #1
0
        public async Task Demo_sources_pass_verification()
        {
            var console = new TestConsole();

            var demoSourcesDir = new DirectoryInfo(@"c:\dev\agent\docs\gettingstarted");
            var packageFile    = demoSourcesDir.Subdirectory("Snippets")
                                 .File("Snippets.csproj");

            _output.WriteLine(demoSourcesDir.FullName);
            _output.WriteLine(packageFile.FullName);

            await DemoCommand.Do(new DemoOptions(output : demoSourcesDir), console);

            var resultCode = await VerifyCommand.Do(
                new VerifyOptions(dir : demoSourcesDir),
                console,
                () => new FileSystemDirectoryAccessor(demoSourcesDir),
                new PackageRegistry(),
                new StartupOptions(package : packageFile.FullName));

            _output.WriteLine(console.Out.ToString());
            _output.WriteLine(console.Error.ToString());

            resultCode.Should().Be(0);
        }
Example #2
0
        public async Task WhenVerifySourceIsLargerThanDestinationThenResultIsSizeNotEqualError()
        {
            // arrange
            var sourcePath              = $"{Guid.NewGuid()}.img";
            var destinationPath         = $"{Guid.NewGuid()}.img";
            var fakeCommandHelper       = new FakeCommandHelper();
            var cancellationTokenSource = new CancellationTokenSource();
            var testDataBytes           = fakeCommandHelper.CreateTestData();

            // create source
            fakeCommandHelper.ReadableMedias.Add(new Media(sourcePath, sourcePath, testDataBytes.Length * 2,
                                                           Media.MediaType.Raw, false,
                                                           new MemoryStream(testDataBytes.Concat(testDataBytes).ToArray())));

            // create destination
            fakeCommandHelper.ReadableMedias.Add(new Media(destinationPath, destinationPath, testDataBytes.Length,
                                                           Media.MediaType.Raw, false,
                                                           new MemoryStream(testDataBytes)));

            // act - verify source img to destination img
            var verifyCommand =
                new VerifyCommand(new NullLogger <VerifyCommand>(), fakeCommandHelper, new List <IPhysicalDrive>(),
                                  sourcePath, destinationPath);
            var result = await verifyCommand.Execute(cancellationTokenSource.Token);

            Assert.False(result.IsSuccess);

            Assert.Equal(typeof(SizeNotEqualError), result.Error.GetType());
            var sizeNotEqualError = (SizeNotEqualError)result.Error;

            Assert.Equal(0, sizeNotEqualError.Offset);
            Assert.Equal(testDataBytes.Length * 2, sizeNotEqualError.Size);
        }
Example #3
0
        public async Task WhenVerifySourceToImgDestinationThenReadDataIsIdentical()
        {
            // arrange
            var sourcePath              = $"{Guid.NewGuid()}.img";
            var destinationPath         = $"{Guid.NewGuid()}.img";
            var fakeCommandHelper       = new FakeCommandHelper(new[] { sourcePath, destinationPath });
            var cancellationTokenSource = new CancellationTokenSource();

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

            verifyCommand.DataProcessed += (_, args) => { dataProcessedEventArgs = args; };
            await verifyCommand.Execute(cancellationTokenSource.Token);

            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);
        }
Example #4
0
        public async Task WhenVerifySourceSmallerThanDestinationThenDataIsIdentical()
        {
            // arrange
            var sourcePath              = $"{Guid.NewGuid()}.img";
            var destinationPath         = $"{Guid.NewGuid()}.img";
            var fakeCommandHelper       = new FakeCommandHelper();
            var cancellationTokenSource = new CancellationTokenSource();
            var testDataBytes           = fakeCommandHelper.CreateTestData();

            // create source
            fakeCommandHelper.ReadableMedias.Add(new Media(sourcePath, sourcePath, testDataBytes.Length,
                                                           Media.MediaType.Raw, false,
                                                           new MemoryStream(testDataBytes)));

            // create destination
            fakeCommandHelper.ReadableMedias.Add(new Media(destinationPath, destinationPath, testDataBytes.Length * 2,
                                                           Media.MediaType.Raw, false,
                                                           new MemoryStream(testDataBytes.Concat(testDataBytes).ToArray())));

            // act - verify source img to destination img
            var verifyCommand =
                new VerifyCommand(new NullLogger <VerifyCommand>(), fakeCommandHelper, new List <IPhysicalDrive>(),
                                  sourcePath, destinationPath);
            var result = await verifyCommand.Execute(cancellationTokenSource.Token);

            Assert.True(result.IsSuccess);
        }
Example #5
0
        public InteractiveConsole()
        {
            _commands              = new Dictionary <string, ICommand>();
            _commands["help"]      = new HelpCommand(this, _commands);
            _commands["magic"]     = new MagicCommand(this);
            _commands["aperft"]    = new AdvancedPerftCommand(this);
            _commands["dperft"]    = new DividedPerftCommand(this);
            _commands["perft"]     = new SimplePerftCommand(this);
            _commands["benchmark"] = new BenchmarkCommand(this);
            _commands["verify"]    = new VerifyCommand(this);
            _commands["evaluate"]  = new EvaluateCommand(this);
            _commands["tuner"]     = new TunerCommand(this);
            _commands["uci"]       = new UciCommand(this);
            _commands["quit"]      = new QuitCommand(this);

            _symbols = new List <string> {
                "%", "s", "ns", "MN/s", "ML/s"
            };

            _keywordColor = ConsoleColor.Cyan;
            _moveColor    = ConsoleColor.Red;
            _numberColor  = ConsoleColor.Yellow;
            _symbolColor  = ConsoleColor.Yellow;

            CultureInfo.CurrentCulture = new CultureInfo("en-US", false);
        }
Example #6
0
        public async Task When_the_template_is_installed_verify_works()
        {
            var baseDirectory   = Create.EmptyWorkspace().Directory;
            var outputDirectory = baseDirectory.CreateSubdirectory("outputTemplate");

            await InstallTemplateAndCreateProject(baseDirectory, outputDirectory);

            var dotnet = new Dotnet(outputDirectory);
            //The template targets 3.0 hence verify should run against 3.0 and not 2.1.503 used in the solution directory
            await dotnet.New("global.json", "--sdk-version 3.0.100-preview6-012264");

            var console           = new TestConsole();
            var directoryAccessor = new FileSystemDirectoryAccessor(outputDirectory);

            var resultCode = await VerifyCommand.Do(
                new VerifyOptions(outputDirectory),
                console,
                () => directoryAccessor,
                PackageRegistry.CreateForTryMode(outputDirectory));

            console.Out
            .ToString()
            .EnforceLF()
            .Trim()
            .Should()
            .Match(
                $"{outputDirectory}{Path.DirectorySeparatorChar}Readme.md*Line *:*{outputDirectory}{Path.DirectorySeparatorChar}Program.cs (in project {outputDirectory}{Path.DirectorySeparatorChar}{outputDirectory.Name}.csproj)*".EnforceLF());

            resultCode.Should().Be(0);
        }
        public async Task When_the_template_is_installed_verify_works()
        {
            var baseDirectory   = Create.EmptyWorkspace().Directory;
            var outputDirectory = baseDirectory.CreateSubdirectory("outputTemplate");

            await InstallTemplateAndCreateProject(baseDirectory, outputDirectory);

            var console           = new TestConsole();
            var directoryAccessor = new FileSystemDirectoryAccessor(outputDirectory);

            var resultCode = await VerifyCommand.Do(
                new VerifyOptions(outputDirectory),
                console,
                () => directoryAccessor,
                PackageRegistry.CreateForTryMode(outputDirectory));

            console.Out
            .ToString()
            .EnforceLF()
            .Trim()
            .Should()
            .Match(
                $"{outputDirectory}{Path.DirectorySeparatorChar}Readme.md*Line 24:*{outputDirectory}{Path.DirectorySeparatorChar}Program.cs (in project {outputDirectory}{Path.DirectorySeparatorChar}{outputDirectory.Name}.csproj)*".EnforceLF());

            resultCode.Should().Be(0);
        }
Example #8
0
        /// <summary>
        /// Instruct the verify command to also verify the contents of the large files repository.
        /// </summary>
        /// <param name="command">
        /// The <see cref="VerifyCommand"/> to modify.
        /// </param>
        /// <param name="revision">
        /// The revision to verify.
        /// Defaults to <see cref="LargeFilesRevisions.Current"/>.
        /// </param>
        /// <param name="verify">
        /// What to verify.
        /// Defaults to <see cref="LargeFilesVerification.Existance"/>.
        /// </param>
        /// <returns>
        /// The <see cref="VerifyCommand"/>, for a fluent interface.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="command"/> is <c>null</c>.
        /// </exception>
        public static VerifyCommand WithVerifyLargeFiles(this VerifyCommand command, LargeFilesRevisions revision = LargeFilesRevisions.Current, LargeFilesVerification verify = LargeFilesVerification.Existance)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            command.AddArgument("--large");

            switch (revision)
            {
            case LargeFilesRevisions.Current:
                break;

            case LargeFilesRevisions.AllRevisions:
                command.AddArgument("--lfa");
                break;
            }

            switch (verify)
            {
            case LargeFilesVerification.Existance:
                break;

            case LargeFilesVerification.Content:
                command.AddArgument("--lfc");
                break;
            }

            return(command);
        }
Example #9
0
            public async Task Errors_are_written_to_std_out()
            {
                var root = new DirectoryInfo(Directory.GetDirectoryRoot(Directory.GetCurrentDirectory()));

                var directoryAccessor = new InMemoryDirectoryAccessor(root, root)
                {
                    ("doc.md", @"
This is some sample code:
```cs --source-file Program.cs
```
")
                };

                var console = new TestConsole();

                await VerifyCommand.Do(
                    new VerifyOptions(root),
                    console,
                    () => directoryAccessor,
                    PackageRegistry.CreateForTryMode(root));

                console.Out
                .ToString()
                .Should()
                .Match($"*{root}doc.md*Line 3:*{root}Program.cs (in project UNKNOWN)*File not found: ./Program.cs*No project file or package specified*");
            }
        public async ValueTask Handle(IBackgroundTaskContext context)
        {
            if (context.BackgroundTask is not ImageFileVerifyBackgroundTask verifyBackgroundTask)
            {
                return;
            }

            try
            {
                var commandHelper = new CommandHelper();
                var verifyCommand =
                    new VerifyCommand(loggerFactory.CreateLogger <VerifyCommand>(), commandHelper,
                                      Enumerable.Empty <IPhysicalDrive>(), verifyBackgroundTask.SourcePath,
                                      verifyBackgroundTask.DestinationPath);
                verifyCommand.DataProcessed += async(_, args) =>
                {
                    await progressHubContext.SendProgress(new Progress
                    {
                        Title               = verifyBackgroundTask.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 verifyCommand.Execute(context.Token);

                await progressHubContext.SendProgress(new Progress
                {
                    Title           = verifyBackgroundTask.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           = verifyBackgroundTask.Title,
                    IsComplete      = true,
                    HasError        = true,
                    ErrorMessage    = e.Message,
                    PercentComplete = 100
                }, context.Token);
            }
        }
Example #11
0
        public async Task NotSupported()
        {
            var channel = new MockSmtpChannel();
            var command = new VerifyCommand(channel);
            await command.ExecuteAsync(CancellationToken.None);

            SmtpTestHelper.AssertResponse(channel, SmtpReplyCode.CannotVerify);
        }
 private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
 {
     switch (e.PropertyName)
     {
     case nameof(Code):
         VerifyCommand.RaiseCanExecuteChanged();
         break;
     }
 }
Example #13
0
        public void RunCorrectVerifierForUser(FakeLevelsProvider provider, string levelId, string user)
        {
            var mockVerifier = new MockVerifier();
            var command      = new VerifyCommand(provider, mockVerifier);

            command.Execute(levelId, user);

            Assert.Equal(levelId, mockVerifier.Level.Id);
            Assert.Equal(user, mockVerifier.User);
        }
Example #14
0
        public void ThrowWhenTooFewParametersPassed(string[] args, string expected)
        {
            var verifier = new MockVerifier();
            var provider = new CustomFakeLevelsProvider();
            var command  = new VerifyCommand(provider, verifier);

            var e = Assert.Throws <InvalidCommandArrayException>(() => command.Execute(args));

            Assert.Equal(expected, e.Message);
        }
Example #15
0
 public async Task <IActionResult> Verify([FromBody] VerifyCommand command)
 {
     try
     {
         return(Ok(await Mediator.Send(command)));
     }
     catch (UnauthorizedAccessException e)
     {
         return(Unauthorized(e.Message));
     }
 }
Example #16
0
        public void ReturnResultFromVerifier(VerifierResult toReturn)
        {
            var verifier = new MockVerifier()
            {
                Return = toReturn
            };
            var provider = new CustomFakeLevelsProvider()
            {
                Level = null
            };
            var command = new VerifyCommand(provider, verifier);

            var result = command.Execute("", "");

            Assert.Equal(toReturn, result);
        }
Example #17
0
        public async Task Demo_returns_an_error_if_the_output_directory_is_not_empty()
        {
            var console = new TestConsole();

            var outputDirectory = Create.EmptyWorkspace().Directory;

            File.WriteAllText(Path.Combine(outputDirectory.FullName, "a file.txt"), "");

            await DemoCommand.Do(
                new DemoOptions(output : outputDirectory),
                console,
                startServer : (options, context) => { });

            var resultCode = await VerifyCommand.Do(
                new VerifyOptions(new FileSystemDirectoryAccessor(outputDirectory)),
                console);

            resultCode.Should().NotBe(0);
        }
Example #18
0
        public async Task Demo_project_passes_verification()
        {
            var console = new TestConsole();

            var outputDirectory = Create.EmptyWorkspace().Directory;
            var packageFile     = outputDirectory.Subdirectory("Snippets")
                                  .File("Snippets.csproj");

            await DemoCommand.Do(new DemoOptions(output : outputDirectory), console);

            var resultCode = await VerifyCommand.Do(
                new VerifyOptions(new FileSystemDirectoryAccessor(outputDirectory)),
                console,
                startupOptions : new StartupOptions(package: packageFile.FullName));

            _output.WriteLine(console.Out.ToString());
            _output.WriteLine(console.Error.ToString());

            resultCode.Should().Be(0);
        }
Example #19
0
        public async Task WhenVerifySourceToImgDestinationWithDifferentBytesAtOffsetThenResultIsByteNotEqualError()
        {
            // arrange
            const int  offsetWithError         = 8390;
            const byte sourceByte              = 178;
            const byte destinationByte         = 250;
            var        sourcePath              = $"{Guid.NewGuid()}.img";
            var        destinationPath         = $"{Guid.NewGuid()}.img";
            var        fakeCommandHelper       = new FakeCommandHelper();
            var        cancellationTokenSource = new CancellationTokenSource();

            // create source
            var sourceBytes = fakeCommandHelper.CreateTestData();

            sourceBytes[offsetWithError] = sourceByte;
            fakeCommandHelper.ReadableMedias.Add(new Media(sourcePath, sourcePath, sourceBytes.Length,
                                                           Media.MediaType.Raw, false,
                                                           new MemoryStream(sourceBytes)));

            // create destination
            var destinationBytesWithError = fakeCommandHelper.CreateTestData();

            destinationBytesWithError[offsetWithError] = destinationByte;
            fakeCommandHelper.ReadableMedias.Add(new Media(destinationPath, destinationPath,
                                                           destinationBytesWithError.Length, Media.MediaType.Raw, false,
                                                           new MemoryStream(destinationBytesWithError)));

            // act - verify source img to destination img
            var verifyCommand =
                new VerifyCommand(new NullLogger <VerifyCommand>(), fakeCommandHelper, new List <IPhysicalDrive>(),
                                  sourcePath, destinationPath);
            var result = await verifyCommand.Execute(cancellationTokenSource.Token);

            Assert.False(result.IsSuccess);
            Assert.Equal(typeof(ByteNotEqualError), result.Error.GetType());
            var byteNotEqualError = (ByteNotEqualError)result.Error;

            Assert.Equal(offsetWithError, byteNotEqualError.Offset);
            Assert.Equal(sourceByte, byteNotEqualError.SourceByte);
            Assert.Equal(destinationByte, byteNotEqualError.DestinationByte);
        }
Example #20
0
        public async Task Demo_starts_the_server_if_there_are_no_errors()
        {
            var console = new TestConsole();

            var outputDirectory = Create.EmptyWorkspace().Directory;

            StartupOptions startupOptions = null;
            await DemoCommand.Do(
                new DemoOptions(output : outputDirectory),
                console,
                (options, context) => startupOptions = options);

            await VerifyCommand.Do(
                new VerifyOptions(new FileSystemDirectoryAccessor(outputDirectory)),
                console);

            _output.WriteLine(console.Out.ToString());
            _output.WriteLine(console.Error.ToString());

            startupOptions.Uri.Should().Be(new Uri("QuickStart.md", UriKind.Relative));
        }
Example #21
0
        private void VerifyCommandArgs(Action <Mock <IVerifyCommandRunner>, CommandLineApplication, Func <LogLevel> > verify)
        {
            // Arrange
            var logLevel          = LogLevel.Information;
            var logger            = new TestCommandOutputLogger();
            var testApp           = new CommandLineApplication();
            var mockCommandRunner = new Mock <IVerifyCommandRunner>();

            mockCommandRunner
            .Setup(m => m.ExecuteCommandAsync(It.IsAny <VerifyArgs>()))
            .Returns(Task.FromResult(0));

            testApp.Name = "dotnet nuget_test";
            VerifyCommand.Register(testApp,
                                   () => logger,
                                   ll => logLevel = ll,
                                   () => mockCommandRunner.Object);

            // Act & Assert
            verify(mockCommandRunner, testApp, () => logLevel);
        }
Example #22
0
        public async Task Demo_sources_pass_verification()
        {
            var console = new TestConsole();

            var demoSourcesDir = Create.EmptyWorkspace().Directory;
            var packageFile    = demoSourcesDir.Subdirectory("Snippets")
                                 .File("Snippets.csproj");

            _output.WriteLine(demoSourcesDir.FullName);
            _output.WriteLine(packageFile.FullName);

            await DemoCommand.Do(new DemoOptions(output : demoSourcesDir), console);

            var resultCode = await VerifyCommand.Do(
                new VerifyOptions(new FileSystemDirectoryAccessor(demoSourcesDir)),
                console);

            _output.WriteLine(console.Out.ToString());
            _output.WriteLine(console.Error.ToString());

            resultCode.Should().Be(0);
        }
Example #23
0
        public async Task WhenVerifySourceToVhdDestinationThenReadDataIsIdentical()
        {
            // 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();
            await fakeCommandHelper.AppendWriteableMediaDataVhd(destinationPath, sourceBytes.Length, sourceBytes);

            // act - verify source img to destination img
            var verifyCommand = new VerifyCommand(new NullLogger <VerifyCommand>(), fakeCommandHelper,
                                                  new List <IPhysicalDrive>(), sourcePath, destinationPath);
            var result = await verifyCommand.Execute(cancellationTokenSource.Token);

            Assert.True(result.IsSuccess);

            // delete destination path vhd
            File.Delete(destinationPath);
        }
Example #24
0
        public async Task WhenVerifySourceToImgDestinationWithDifferentSizesThenResultIsSizeNotEqualError()
        {
            // arrange
            var sourcePath              = $"{Guid.NewGuid()}.img";
            var destinationPath         = $"{Guid.NewGuid()}.img";
            var fakeCommandHelper       = new FakeCommandHelper();
            var cancellationTokenSource = new CancellationTokenSource();

            // create source
            var sourceBytes = fakeCommandHelper.CreateTestData();

            fakeCommandHelper.ReadableMedias.Add(new Media(sourcePath, sourcePath, sourceBytes.Length,
                                                           Media.MediaType.Raw, false,
                                                           new MemoryStream(sourceBytes)));

            // create destination
            var destinationSize       = sourceBytes.Length / 2;
            var destinationBytesChunk = new byte[Convert.ToInt32(destinationSize)];

            Array.Copy(sourceBytes, 0, destinationBytesChunk, 0, destinationBytesChunk.Length);
            fakeCommandHelper.ReadableMedias.Add(new Media(destinationPath, destinationPath, destinationSize,
                                                           Media.MediaType.Raw, false,
                                                           new MemoryStream(destinationBytesChunk)));

            // act - verify source img to destination img
            var verifyCommand =
                new VerifyCommand(new NullLogger <VerifyCommand>(), fakeCommandHelper, new List <IPhysicalDrive>(),
                                  sourcePath, destinationPath);
            var result = await verifyCommand.Execute(cancellationTokenSource.Token);

            Assert.False(result.IsSuccess);

            Assert.Equal(typeof(SizeNotEqualError), result.Error.GetType());
            var sizeNotEqualError = (SizeNotEqualError)result.Error;

            Assert.Equal(0, sizeNotEqualError.Offset);
            Assert.Equal(sourceBytes.Length, sizeNotEqualError.Size);
        }
Example #25
0
        public async Task WhenVerifySourceToImgDestinationWithSizeThenReadDataIsIdentical()
        {
            // arrange
            var sourcePath              = $"{Guid.NewGuid()}.img";
            var destinationPath         = $"{Guid.NewGuid()}.img";
            var size                    = 16 * 512;
            var fakeCommandHelper       = new FakeCommandHelper(new[] { sourcePath, destinationPath });
            var cancellationTokenSource = new CancellationTokenSource();

            // act - verify source img to destination img
            var verifyCommand = new VerifyCommand(new NullLogger <VerifyCommand>(), fakeCommandHelper,
                                                  new List <IPhysicalDrive>(), sourcePath,
                                                  destinationPath, size);
            var result = await verifyCommand.Execute(cancellationTokenSource.Token);

            Assert.True(result.IsSuccess);

            // assert data is identical
            var sourceBytes      = fakeCommandHelper.GetMedia(sourcePath).GetBytes(size);
            var destinationBytes = fakeCommandHelper.GetMedia(destinationPath).GetBytes(size);

            Assert.Equal(sourceBytes, destinationBytes);
        }
Example #26
0
 public async Task <ActionResult <UserDto> > Verify([FromBody] VerifyCommand command)
 {
     return(await Mediator.Send(command));
 }
Example #27
0
 public void Handle(ICommandContext context, VerifyCommand command)
 {
     context.Get <Grantee>(command.AggregateRootId).Verify();
 }
Example #28
0
        public async Task <ActionResult> Verify([FromBody] VerifyCommand command)
        {
            await Mediator.Send(command);

            return(NoContent());
        }
Example #29
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;
            }
        }