public async ValueTask Handle(IBackgroundTaskContext context) { if (context.BackgroundTask is not PhysicalDriveInfoBackgroundTask infoBackgroundTask) { return; } var physicalDrives = await physicalDriveManager.GetPhysicalDrives(); var commandHelper = new CommandHelper(); var logger = loggerFactory.CreateLogger <InfoCommand>(); var infoCommand = new InfoCommand(logger, commandHelper, physicalDrives, infoBackgroundTask.Path); infoCommand.DiskInfoRead += async(_, args) => { await resultHubConnection.SendInfoResult(args.MediaInfo.ToViewModel()); }; var result = await infoCommand.Execute(context.Token); if (result.IsFaulted) { await errorHubConnection.UpdateError(result.Error.Message, context.Token); } }
public void Add(List <string> keywords, string informationText, string helpText, string username) { using (var context = _chatbotContextFactory.Create()) { if (context.InfoCommandKeywords.Any(ik => keywords.Contains(ik.InfoCommandKeywordText))) { throw new Exception("A command with one or more of the provided aliases already exists"); } var infoCommand = new InfoCommand { InfoText = "{0}" + informationText, InfoHelpText = "Hey @{0}! " + helpText, AddedByUser = username }; context.InfoCommands.Add(infoCommand); context.SaveChanges(); var infoCommandKeywords = keywords.Select(k => new InfoCommandKeyword { InfoCommandId = infoCommand.InfoCommandId, InfoCommandKeywordText = k }); context.InfoCommandKeywords.AddRange(infoCommandKeywords); context.SaveChanges(); } }
public JsonResult Info(string instance, [FromQuery] InfoCommand model) { // Just return serialized model for now. var result = new JsonResult(model); return(result); }
public Command GetCommand(ReportLevel reportLevel, string dateTime, string message) { Command cmd = null; switch (reportLevel) { case ReportLevel.Info: cmd = new InfoCommand(dateTime, reportLevel, message); break; case ReportLevel.Warning: cmd = new WarningCommand(dateTime, reportLevel, message); break; case ReportLevel.Error: cmd = new ErrorCommand(dateTime, reportLevel, message); break; case ReportLevel.Critical: cmd = new CriticalCommand(dateTime, reportLevel, message); break; case ReportLevel.Fatal: cmd = new FatalCommand(dateTime, reportLevel, message); break; } return(cmd); }
internal static T GetDeviceData <T>(IntPtr deviceHandle, InfoCommand command, Func <IntPtr, T> dataGetter) { uint dataSize = 0; var data = IntPtr.Zero; GetRawInputDeviceInfo(deviceHandle, command, data, ref dataSize); if (dataSize == 0) { return(default);
public async Task ItShouldRunInfoCommand() { var command = new InfoCommand( Mock.Of <IApplicationInfo>(), Mock.Of <ILogger <InfoCommand> >()); Func <Task <int> > act = async() => await command.OnExecuteAsync(); act.Should().NotThrow(); }
private static void RunCommands(object obj) { // todo: copied code switch (obj) { case ContextMenuCommand c1: { var c = (IIntegrated)c1; RunIntegrated(c, ContextMenuCommand.Add, ContextMenuCommand.Remove); break; } case PathCommand c1: { var c = (IIntegrated)c1; RunIntegrated(c, PathCommand.Add, PathCommand.Remove); break; } case CreateSauceNaoCommand c: { var acc = SauceNao.CreateAccount(c.Auto); CliOutput.WriteInfo("Account information:"); var accStr = acc.ToString(); var output = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\saucenao_account.txt"; File.WriteAllText(output, accStr); Console.WriteLine(accStr); CliOutput.WriteInfo("Adding key to cfg file"); RuntimeInfo.Config.SauceNaoAuth = acc.ApiKey; RuntimeInfo.Config.WriteToFile(); break; } case ResetCommand c: { ResetCommand.RunReset(c.All); break; } case InfoCommand c: { InfoCommand.Show(); break; } } }
protected void InfoCommandHandler(InfoCommand cmd) { #if PERFORMANCE_TEST var ptest = Service.Performance.PerformanceTest.Get(); ptest.Start("InfoCommand"); #endif _service.Info(cmd.message, cmd.domain); #if PERFORMANCE_TEST // now stop the watches ptest.Stop("InfoCommand"); #endif }
public static bool TryParse(string s, out ICommand <T> command) { command = null; if (s.StartsWith("!markov-info")) { command = new InfoCommand(); return(true); } return(false); }
public MatchViewModel() { //ProfileDataInstance = ProfileData.Instance; //Questions = ProfileData.Instance.Questions; //Profiles = ProfileData.Instance.Profiles; //AssertiveListView = assertiveListView; TapCommand = new Command <Assertive>(AssertiveTap); ProfileQuestionCommand = new ProfileQuestionTapCommand(this); //InfoButtonClickedCommand = new Command<object>(InfoButtonClicked); InfoCommand = new InfoCommand(this); LeftCommand = new LeftCommand(this); RightCommand = new RightCommand(this); LeftEnabled = false; RightEnabled = true; }
public async Task WhenReadInfoFromSourceImgWithRigidDiskBlockThenDiskInfoIsReturned() { // arrange var path = Path.Combine("TestData", "rigid-disk-block.img"); var fakeCommandHelper = new FakeCommandHelper(new[] { path }); var cancellationTokenSource = new CancellationTokenSource(); // read info from path var infoCommand = new InfoCommand(new NullLogger <InfoCommand>(), fakeCommandHelper, Enumerable.Empty <IPhysicalDrive>(), path); MediaInfo mediaInfo = null; infoCommand.DiskInfoRead += (_, args) => { mediaInfo = args.MediaInfo; }; await infoCommand.Execute(cancellationTokenSource.Token); // assert media info Assert.NotNull(mediaInfo); //Assert.Equal(mediaInfo.DiskSize, FakeCommandHelper.ImageSize); Assert.NotNull(mediaInfo.RigidDiskBlock); }
public void Execute(IContext <T> context, Action next) { if (PrivateMessage.TryParse(context.Message, out var message)) { ICommand <T> cmd; if (SaveCommand.TryParse(message.Text, out cmd)) { cmd.Execute(context); } else if (InfoCommand.TryParse(message.Text, out cmd)) { cmd.Execute(context); } else if (ContainsOwnRef(context, message.Text)) { Log.Debug("Eager to respond (contains own ref)"); var resp = RandomResponse(context); context.Client.Say(resp); this.lastResponse = DateTime.Now; } else { var t = DateTime.Now.Subtract(this.lastResponse); if (t.TotalSeconds < 10) { Log.Debug("Eager to respond (believes to be in convo)"); var resp = RandomResponse(context); context.Client.Say(resp); this.lastResponse = DateTime.Now; } } Log.Debug("[NOTRIG] Updating memory"); Update(context.Session, message.Text); } next(); }
public async Task WhenReadInfoFromSourceImgThenDiskInfoIsReturned() { // arrange var path = $"{Guid.NewGuid()}.img"; var fakeCommandHelper = new FakeCommandHelper(new[] { path }); var cancellationTokenSource = new CancellationTokenSource(); // read info from path var infoCommand = new InfoCommand(new NullLogger <InfoCommand>(), fakeCommandHelper, Enumerable.Empty <IPhysicalDrive>(), path); MediaInfo mediaInfo = null; infoCommand.DiskInfoRead += (_, args) => { mediaInfo = args.MediaInfo; }; var result = await infoCommand.Execute(cancellationTokenSource.Token); Assert.True(result.IsSuccess); // assert media info Assert.NotNull(mediaInfo); Assert.Equal(mediaInfo.DiskSize, FakeCommandHelper.ImageSize); Assert.Null(mediaInfo.RigidDiskBlock); }
public JsonResult Info(string instance, [FromQuery] InfoCommand model) { var result = new JsonResult(model); return(result); }
private static int Main(string[] arguments) { // Configure logging. var loggingLevelSwitch = new LoggingLevelSwitch { MinimumLevel = LogEventLevel.Information }; Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(loggingLevelSwitch) .WriteTo.Console() .CreateLogger(); var showHelp = false; var argumentParser = new ArgumentParser(); argumentParser.Add("help|version|?", "Show this message.", (value) => { showHelp = true; }); argumentParser.Add("verbose|v", "Increase amount of log messages.", (value) => loggingLevelSwitch.MinimumLevel = LogEventLevel.Debug); // Handle all exceptions by showing them in the console try { var commandArgument = arguments.Length > 0 ? arguments[0] : "help"; BaseCommand?command = null; switch (commandArgument) { case "extract": command = new ExtractCommand(argumentParser); break; case "info": command = new InfoCommand(argumentParser); break; case "audio": command = new AudioCommand(argumentParser); break; case "items": command = new ItemsCommand(argumentParser); break; case "help": case "--help": case "--version": commandArgument = "help"; break; } if (command == null) { Program.ShowHelp(argumentParser, commandArgument); return(commandArgument == "help" ? Program.ExitCodeOk : Program.ExitCodeInvalidArgument); } command.Configure(arguments.Skip(1)); // Show help, now with configured argument parser for command-specific help. if (showHelp) { Program.ShowHelp(argumentParser, commandArgument); return(Program.ExitCodeOk); } if (argumentParser.UnparsedArguments.Any()) { // Do not accept invalid arguments because they usually indicate faulty usage foreach (var unparsedArgument in argumentParser.UnparsedArguments) { Console.WriteLine($"Unknown argument \"{unparsedArgument}\"."); } Console.WriteLine(); Program.ShowHelp(argumentParser, commandArgument); return(Program.ExitCodeInvalidArgument); } var exitCode = command.Run(); if (exitCode == Program.ExitCodeInvalidArgument) { Console.WriteLine(); Program.ShowHelp(argumentParser, commandArgument); } return(exitCode); } catch (System.Exception exception) { // Use first exception in aggregates for easier debugging. while (exception is AggregateException && exception.InnerException != null) { exception = exception.InnerException; } // Rethrow for debugger to process. if (Debugger.IsAttached) { throw; } Log.Fatal(exception.Message + "\n" + exception.StackTrace); return(Program.ExitCodeError); } }
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; } }
static int HandleArguments(string[] args) { if (args.Length == 0) { Console.WriteLine("Try running `stuff help`"); return(1); } var command = args[0]; var shifted = args.Skip(1).ToArray(); var _options = new List <string>(); int i; for (i = 0; i < args.Length; i++) { if (args[i] == "--") { break; } else if (args[i].StartsWith("--")) { _options.Add(args[i]); } else { break; } } var options = _options.ToArray(); switch (command) { case "search": case "s": return(SearchCommand.HandleCommandLine(shifted, options)); case "ksp": return(KSPCommand.HandleCommandLine(shifted, options)); case "info": return(InfoCommand.HandleCommandLine(shifted, options)); case "changelog": return(ChangelogCommand.HandleCommandLine(shifted, options)); case "download": return(DownloadCommand.HandleCommandLine(shifted, options)); case "help": Console.WriteLine( "\nStuffManager Commands:\n\n" + "\tsearch -- Search KerbalStuff\n" + "\tksp -- Run KSP\n" + "\tinfo -- Provide info about a mod\n" + "\tchangelog -- Display a mod's changelog\n" + "\tdownload -- Download a mod\n" + "\thelp -- Display this help\n" ); return(0); } Console.WriteLine("Command not found. Try `stuff help`."); return(1); }