Inheritance: ICommand
示例#1
0
 public void ExecuteShouldShowHelpView()
 {
     var viewMock = new Mock<IHelpView>();
     ICommand target = new HelpCommand(viewMock.Object);
     target.Execute();
     viewMock.Verify(v => v.Show());
 }
示例#2
0
        public int Invoke(string[] args)
        {
            try
            {
                HelpCommand = new HelpCommand(Manager, "galops", "NuGet Gallery Operations", "https://github.com/NuGet/NuGetOperations/wiki/GalOps---Gallery-Operations-Commands");

                // Add commands
                foreach (ICommand cmd in Commands)
                {
                    Manager.RegisterCommand(cmd);
                }

                var secretReaderFactory = new SecretReaderFactory(ConfigurationManager.AppSettings);

                var configurationProcessor = new ConfigurationProcessor(secretReaderFactory);
                configurationProcessor.InjectSecretsInto(ConfigurationManager.AppSettings);

                // Parse the command
                var parser = new CommandLineParser(Manager, secretReaderFactory);
                ICommand command = parser.ParseCommandLine(args) ?? HelpCommand;

                // Fall back on help command if we failed to parse a valid command
                if (!ArgumentCountValid(command))
                {
                    string commandName = command.CommandAttribute.CommandName;
                    Console.WriteLine("{0}: invalid arguments..", commandName);
                    HelpCommand.ViewHelpForCommand(commandName);
                }
                else
                {
                    command.Execute();
                }
            }
            catch (AggregateException exception)
            {
                string message;
                Exception unwrappedEx = ExceptionUtility.Unwrap(exception);
                if (unwrappedEx == exception)
                {
                    // If the AggregateException contains more than one InnerException, it cannot be unwrapped. In which case, simply print out individual error messages
                    message = String.Join(Environment.NewLine, exception.InnerExceptions.Select(ex => ex.Message).Distinct(StringComparer.CurrentCulture));
                }
                else
                {
                    message = ExceptionUtility.Unwrap(exception).Message;
                }
                _logger.Error("{0}: {1}", unwrappedEx.GetType().Name, message);
                _logger.Error(" Stack Trace: " + unwrappedEx.StackTrace);
                return 1;
            }
            catch (Exception e)
            {
                var ex = ExceptionUtility.Unwrap(e);
                _logger.Error("{0}: {1}", ex.GetType().Name, ex.Message);
                _logger.Error(" Stack Trace: " + ex.StackTrace);
                return 1;
            }
            return 0;
        }
 public void SutIsCommand(HelpCommand sut)
 {
     // Fixture setup
     // Exercise system
     // Verify outcome
     Assert.IsAssignableFrom<ICommand>(sut);
     // Teardown
 }
示例#4
0
		void RunCommand(HelpCommand command)
		{
			switch (command)
			{
				case HelpCommand.Help_About: About.AboutWindow.Run(); break;
				case HelpCommand.Help_License: About.LicenseWindow.Run(); break;
				case HelpCommand.Help_RunGC: GC.Collect(); break;
			}
		}
        protected override ICommand GetHelpCommand()
        {
            if (HelpCommand == null)
            {
                HelpCommand = new HelpCommand(Console);
                HelpCommand.AddLine(string.Format("Help for command {0}. {1}", Name, Description));
                HelpCommand.AddLine(HelpText, CanExecute);
            }

            return HelpCommand;
        }
        public void GetHelpText_ForLogCommand_ReturnsText()
        {
            var command = new HelpCommand
            {
                Topic = "log"
            };
            NonPersistentClient.Execute(command);
            string text = command.Result;

            Assert.That(text, Is.StringContaining("show revision history of entire repository or files"));
        }
        public void GetHelpText_WithoutGlobalOptions_DoesNotIncludeGlobalOptions()
        {
            var command = new HelpCommand
            {
                Topic = "log"
            };
            NonPersistentClient.Execute(command);
            string text = command.Result;

            Assert.That(text, Is.Not.StringContaining("enable debugging output"));
        }
        protected override ICommand GetHelpCommand()
        {
            if (HelpCommand == null)
            {
                HelpCommand = new HelpCommand(Console);
                HelpCommand.AddLine(string.Format("Help for command {0}.", Name));
                HelpCommand.AddLine(string.Empty);

                HelpCommand.AddLine(string.Format("Sub Commands for {0}:", Name));
                foreach (var command in SubCommands) HelpCommand.AddLine(string.Format("{0} {1}", command.Name.PadString(10), command.Description), command.CanExecute);
            }

            return HelpCommand;
        }
        public void ExecuteWillWriteCorrectOutput(HelpCommand sut)
        {
            // Fixture setup
            var expectedOutput = "Usage: UpdateCurrency <DKK | EUR | USD> <DKK | EUR | USD> <rate>." + Environment.NewLine;

            using (var sw = new StringWriter())
            {
                Console.SetOut(sw);
                // Exercise system
                sut.Execute();
                // Verify outcome
                Assert.Equal(expectedOutput, sw.ToString());
                // Teardown
            }
        }
示例#10
0
 private static bool CreateCommand(out Command command,string name, string[] args)
 {
     command = null;
     if (name == "i")
     {
         if (args.Length == 1)
         {
             command = new InstallOnSiteCommand(args[0], _profileeManager);
         }
     }
     else if (name == "u")
     {
         if (args.Length == 1)
         {
             command = new UninstallOnSiteCommand(args[0], _profileeManager);
         }
     }
     else if (name == "s")
     {
         command = new ShowConfigurationCommand(_profileeManager,new ClrConfigurator(System.Console.WriteLine));
     }
     else if (name == "asm")
     {
         if (args.Length == 1)
         {
             command = new ConfigureAssemblyCommand(args[0],new ClrConfigurator(System.Console.WriteLine));
         }
     }
     else if (name == "?")
     {
         if (args.Length == 0)
         {
             command = new HelpCommand();
         }
     }
     return command != null;
 }
示例#11
0
 public override bool TryBuildCommand(string[] args, out object command)
 {
     command = new HelpCommand();
     return true;
 }
        protected virtual CommandCollectionItem CreateHelpCommand()
        {
            HelpCommand helpCommand = new HelpCommand(commands);

            return(new CommandCollectionItem("help", helpCommand));
        }
示例#13
0
        private async void OnTelegramMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.TextMessage)
            {
                return;
            }

            var answerTextmessage = "";

            if (_session.Profile == null || _session.Inventory == null)
            {
                return;
            }
            lastChatId = message.Chat.Id;
            File.WriteAllText(LOG_FILE, lastChatId.ToString());
            var messagetext = message.Text.ToLower().Split(' ');

            if (!_loggedIn && messagetext[0].ToLower().Contains("/login"))
            {
                if (messagetext.Length == 2)
                {
                    if (messagetext[1].ToLower().Contains(_session.LogicSettings.TelegramPassword))
                    {
                        _loggedIn          = true;
                        _lastLoginTime     = DateTime.Now;
                        answerTextmessage += _session.Translation.GetTranslation(TranslationString.LoggedInTelegram);
                        await SendMessage(message.Chat.Id, answerTextmessage);

                        return;
                    }
                    answerTextmessage += _session.Translation.GetTranslation(TranslationString.LoginFailedTelegram);
                    await SendMessage(message.Chat.Id, answerTextmessage);

                    return;
                }
                answerTextmessage += _session.Translation.GetTranslation(TranslationString.NotLoggedInTelegram);
                await SendMessage(message.Chat.Id, answerTextmessage);

                return;
            }
            if (_loggedIn)
            {
                if (_lastLoginTime.AddMinutes(5).Ticks < DateTime.Now.Ticks)
                {
                    _loggedIn          = false;
                    answerTextmessage += _session.Translation.GetTranslation(TranslationString.NotLoggedInTelegram);
                    await SendMessage(message.Chat.Id, answerTextmessage);

                    return;
                }
                var remainingMins = _lastLoginTime.AddMinutes(5).Subtract(DateTime.Now).Minutes;
                var remainingSecs = _lastLoginTime.AddMinutes(5).Subtract(DateTime.Now).Seconds;
                answerTextmessage += _session.Translation.GetTranslation(TranslationString.LoginRemainingTime,
                                                                         remainingMins, remainingSecs);
                await SendMessage(message.Chat.Id, answerTextmessage);

                return;
            }

            if (messagetext[0].ToLower() == "/loc")
            {
                SendLocation(message.Chat.Id, _session.Client.CurrentLatitude, _session.Client.CurrentLongitude);
                return;
            }
            bool            handled           = false;
            Action <string> OnMessageCallback = async(string msg) =>
            {
                try
                {
                    await SendMessage(message.Chat.Id, msg);
                }
                catch (Exception)
                {
                }
            };

            foreach (var item in this.handlers)
            {
                try
                {
                    handled = await item.OnCommand(_session, message.Text, OnMessageCallback);

                    if (handled)
                    {
                        break;
                    }
                }
                catch (Exception)
                {
                }
            }

            if (!handled)
            {
                HelpCommand helpCMD = new HelpCommand();
                await helpCMD.OnCommand(_session, helpCMD.Command, OnMessageCallback);
            }
        }
示例#14
0
    public static void Main(string[] args)
    {
        Driver driver = new Driver(args);
        ServicePointManager.CertificatePolicy = driver;

        if (args.Length == 0) {
            HelpCommand cmd = new HelpCommand(driver, args);
            cmd.Run();
            return;
        }

        // basic auth doesn't seem to work well on mono when POSTing
        // large data sets via a webservice.
        AuthenticationManager.Unregister("Basic");

        try
            {
                driver.ProcessAllCommands();
            }
        catch (TeamFoundationServerException e)
            {
                Console.Error.WriteLine(e.Message);
                //Console.WriteLine(driver.Domain + "\\" + driver.Username);
            }
    }
示例#15
0
        internal static int ProcessArgs(string[] args, ITelemetry telemetryClient = null)
        {
            // CommandLineApplication is a bit restrictive, so we parse things ourselves here. Individual apps should use CLA.

            var success = true;
            var command = string.Empty;
            var lastArg = 0;
            var cliFallbackFolderPathCalculator = new CliFolderPathCalculator();
            TopLevelCommandParserResult topLevelCommandParserResult = TopLevelCommandParserResult.Empty;

            using (INuGetCacheSentinel nugetCacheSentinel = new NuGetCacheSentinel(cliFallbackFolderPathCalculator))
                using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel =
                           new FirstTimeUseNoticeSentinel(cliFallbackFolderPathCalculator))
                {
                    IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel;
                    IAspNetCertificateSentinel  aspNetCertificateSentinel  = new AspNetCertificateSentinel(cliFallbackFolderPathCalculator);
                    for (; lastArg < args.Length; lastArg++)
                    {
                        if (IsArg(args[lastArg], "d", "diagnostics"))
                        {
                            Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString);
                            CommandContext.SetVerbose(true);
                        }
                        else if (IsArg(args[lastArg], "version"))
                        {
                            PrintVersion();
                            return(0);
                        }
                        else if (IsArg(args[lastArg], "info"))
                        {
                            PrintInfo();
                            return(0);
                        }
                        else if (IsArg(args[lastArg], "h", "help") ||
                                 args[lastArg] == "-?" ||
                                 args[lastArg] == "/?")
                        {
                            HelpCommand.PrintHelp();
                            return(0);
                        }
                        else if (args[lastArg].StartsWith("-", StringComparison.OrdinalIgnoreCase))
                        {
                            Reporter.Error.WriteLine($"Unknown option: {args[lastArg]}");
                            success = false;
                        }
                        else
                        {
                            // It's the command, and we're done!
                            command = args[lastArg];
                            if (string.IsNullOrEmpty(command))
                            {
                                command = "help";
                            }

                            topLevelCommandParserResult = new TopLevelCommandParserResult(command);
                            var hasSuperUserAccess = false;
                            if (IsDotnetBeingInvokedFromNativeInstaller(topLevelCommandParserResult))
                            {
                                aspNetCertificateSentinel  = new NoOpAspNetCertificateSentinel();
                                firstTimeUseNoticeSentinel = new NoOpFirstTimeUseNoticeSentinel();
                                hasSuperUserAccess         = true;
                            }

                            ConfigureDotNetForFirstTimeUse(
                                nugetCacheSentinel,
                                firstTimeUseNoticeSentinel,
                                aspNetCertificateSentinel,
                                cliFallbackFolderPathCalculator,
                                hasSuperUserAccess);

                            break;
                        }
                    }
                    if (!success)
                    {
                        HelpCommand.PrintHelp();
                        return(1);
                    }

                    if (telemetryClient == null)
                    {
                        telemetryClient = new Telemetry.Telemetry(firstTimeUseNoticeSentinel);
                    }
                    TelemetryEventEntry.Subscribe(telemetryClient.TrackEvent);
                    TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);
                }

            IEnumerable <string> appArgs =
                (lastArg + 1) >= args.Length
                ? Enumerable.Empty <string>()
                : args.Skip(lastArg + 1).ToArray();

            if (CommandContext.IsVerbose())
            {
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }

            TelemetryEventEntry.SendFiltered(topLevelCommandParserResult);

            int exitCode;

            if (BuiltInCommandsCatalog.Commands.TryGetValue(topLevelCommandParserResult.Command, out var builtIn))
            {
                var parseResult = Parser.Instance.ParseFrom($"dotnet {topLevelCommandParserResult.Command}", appArgs.ToArray());
                if (!parseResult.Errors.Any())
                {
                    TelemetryEventEntry.SendFiltered(parseResult);
                }

                exitCode = builtIn.Command(appArgs.ToArray());
            }
            else
            {
                CommandResult result = Command.Create(
                    "dotnet-" + topLevelCommandParserResult.Command,
                    appArgs,
                    FrameworkConstants.CommonFrameworks.NetStandardApp15)
                                       .Execute();
                exitCode = result.ExitCode;
            }
            return(exitCode);
        }
示例#16
0
 public Program(ICommand command, HelpCommand helpCommand)
 {
     this.command     = command;
     this.helpCommand = helpCommand;
 }
示例#17
0
        internal static int ProcessArgs(string[] args, ITelemetry telemetryClient = null)
        {
            // CommandLineApplication is a bit restrictive, so we parse things ourselves here. Individual apps should use CLA.

            bool?verbose = null;
            var  success = true;
            var  command = string.Empty;
            var  lastArg = 0;

            using (INuGetCacheSentinel nugetCacheSentinel = new NuGetCacheSentinel())
            {
                for (; lastArg < args.Length; lastArg++)
                {
                    if (IsArg(args[lastArg], "v", "verbose"))
                    {
                        verbose = true;
                    }
                    else if (IsArg(args[lastArg], "version"))
                    {
                        PrintVersion();
                        return(0);
                    }
                    else if (IsArg(args[lastArg], "info"))
                    {
                        PrintInfo();
                        return(0);
                    }
                    else if (IsArg(args[lastArg], "h", "help"))
                    {
                        HelpCommand.PrintHelp();
                        return(0);
                    }
                    else if (args[lastArg].StartsWith("-"))
                    {
                        Reporter.Error.WriteLine($"Unknown option: {args[lastArg]}");
                        success = false;
                    }
                    else
                    {
                        ConfigureDotNetForFirstTimeUse(nugetCacheSentinel);

                        // It's the command, and we're done!
                        command = args[lastArg];
                        break;
                    }
                }
                if (!success)
                {
                    HelpCommand.PrintHelp();
                    return(1);
                }

                if (telemetryClient == null)
                {
                    telemetryClient = new Telemetry(nugetCacheSentinel);
                }
            }

            var appArgs = (lastArg + 1) >= args.Length ? Enumerable.Empty <string>() : args.Skip(lastArg + 1).ToArray();

            if (verbose.HasValue)
            {
                Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, verbose.ToString());
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }

            if (string.IsNullOrEmpty(command))
            {
                command = "help";
            }

            telemetryClient.TrackEvent(command, null, null);

            int exitCode;
            Func <string[], int> builtIn;

            if (s_builtIns.TryGetValue(command, out builtIn))
            {
                exitCode = builtIn(appArgs.ToArray());
            }
            else
            {
                CommandResult result = Command.Create("dotnet-" + command, appArgs, FrameworkConstants.CommonFrameworks.NetStandardApp15)
                                       .Execute();
                exitCode = result.ExitCode;
            }

            return(exitCode);
        }
示例#18
0
文件: Program.cs 项目: singhsarab/cli
        private static int ProcessArgs(string[] args)
        {
            // CommandLineApplication is a bit restrictive, so we parse things ourselves here. Individual apps should use CLA.

            bool?verbose = null;
            var  success = true;
            var  command = string.Empty;
            var  lastArg = 0;

            for (; lastArg < args.Length; lastArg++)
            {
                if (IsArg(args[lastArg], "v", "verbose"))
                {
                    verbose = true;
                }
                else if (IsArg(args[lastArg], "version"))
                {
                    PrintVersion();
                    return(0);
                }
                else if (IsArg(args[lastArg], "info"))
                {
                    PrintInfo();
                    return(0);
                }
                else if (IsArg(args[lastArg], "h", "help"))
                {
                    HelpCommand.PrintHelp();
                    return(0);
                }
                else if (args[lastArg].StartsWith("-"))
                {
                    Reporter.Error.WriteLine($"Unknown option: {args[lastArg]}");
                    success = false;
                }
                else
                {
                    // It's the command, and we're done!
                    command = args[lastArg];
                    break;
                }
            }
            if (!success)
            {
                HelpCommand.PrintHelp();
                return(1);
            }

            var appArgs = (lastArg + 1) >= args.Length ? Enumerable.Empty <string>() : args.Skip(lastArg + 1).ToArray();

            if (verbose.HasValue)
            {
                Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, verbose.ToString());
            }

            if (string.IsNullOrEmpty(command))
            {
                command = "help";
            }

            var builtIns = new Dictionary <string, Func <string[], int> >
            {
                ["build"]               = BuildCommand.Run,
                ["compile-csc"]         = CompileCscCommand.Run,
                ["help"]                = HelpCommand.Run,
                ["mcg"]                 = McgCommand.Run,
                ["new"]                 = NewCommand.Run,
                ["pack"]                = PackCommand.Run,
                ["projectmodel-server"] = ProjectModelServerCommand.Run,
                ["publish"]             = PublishCommand.Run,
                ["restore"]             = RestoreCommand.Run,
                ["run"]                 = RunCommand.Run,
                ["test"]                = TestCommand.Run
            };

            Func <string[], int> builtIn;

            if (builtIns.TryGetValue(command, out builtIn))
            {
                return(builtIn(appArgs.ToArray()));
            }

            return(Command.Create("dotnet-" + command, appArgs, FrameworkConstants.CommonFrameworks.NetStandardApp15)
                   .ForwardStdErr()
                   .ForwardStdOut()
                   .Execute()
                   .ExitCode);
        }
示例#19
0
 static public void Remove(HelpCommand helpFunc)
 {
     helpDelegate -= helpFunc;
 }
示例#20
0
 public MenuStripView(FileCommand fileCommand, EditCommand editCommand, FunctionsCommand functionsCommand, ConstantsCommand constantsCommand, ChartCommand chartCommand, TransformCommand transformCommand, ToolsCommand toolsCommand, HelpCommand helpCommand) : this()
 {
     SetCommands(fileCommand, editCommand, functionsCommand, constantsCommand, chartCommand, transformCommand,
                 toolsCommand, helpCommand);
 }
示例#21
0
            public static string Execute(params string[] args)
            {
                int n = 0;

                DaggerfallWorkshop.StreamingWorld streamingWorld = GameManager.Instance.StreamingWorld; //GameObject.FindObjectOfType<DaggerfallWorkshop.StreamingWorld>();
                PlayerEnterExit playerEE = GameManager.Instance.PlayerEnterExit;                        //GameObject.FindObjectOfType<PlayerEnterExit>();

                if (args == null || args.Length < 1)
                {
                    return(HelpCommand.Execute(GotoLocation.name));
                }
                else if (streamingWorld == null)
                {
                    return("Could not locate Streaming world object");
                }
                else if (playerEE == null || playerEE.IsPlayerInside)
                {
                    return("PlayerEnterExit could not be found or player inside");
                }
                else if (int.TryParse(args[0], out n))
                {
                    if (n < 0 || n > 9)
                    {
                        return("Invalid location index");
                    }
                    else
                    {
                        switch (n)
                        {
                        case 0:
                            int xpos, ypos;
                            while (true)
                            {
                                xpos = UnityEngine.Random.Range(0, MapsFile.MaxMapPixelX - 1);
                                ypos = UnityEngine.Random.Range(0, MapsFile.MaxMapPixelY - 1);
                                DaggerfallWorkshop.Utility.ContentReader.MapSummary mapSummary;
                                if (DaggerfallWorkshop.DaggerfallUnity.Instance.ContentReader.HasLocation(xpos, ypos, out mapSummary))
                                {
                                    streamingWorld.TeleportToCoordinates(xpos + 1, ypos - 1);     // random location - locations always seem to be one pixel to the northern east - so compensate for this (since locations are never at the border - there should not occur a index out of bounds...)
                                    return(string.Format("Teleported player to location at: {0}, {1}", xpos, ypos));
                                }
                            }

                        case 1:
                            streamingWorld.TeleportToCoordinates(207, 213, StreamingWorld.RepositionMethods.RandomStartMarker);
                            return("Teleported player to Daggerfall/Daggerfall");

                        case 2:
                            streamingWorld.TeleportToCoordinates(859, 244, StreamingWorld.RepositionMethods.RandomStartMarker);
                            return("Teleported player to Wayrest/Wayrest");

                        case 3:
                            streamingWorld.TeleportToCoordinates(397, 343, StreamingWorld.RepositionMethods.RandomStartMarker);
                            return("Teleported player to Sentinel/Sentinel");

                        case 4:
                            streamingWorld.TeleportToCoordinates(892, 146, StreamingWorld.RepositionMethods.RandomStartMarker);
                            return("Teleported player to Orsinium Area/Orsinium");

                        case 5:
                            streamingWorld.TeleportToCoordinates(67, 119, StreamingWorld.RepositionMethods.RandomStartMarker);
                            return("Teleported player to Tulune/The Old Copperham Place");

                        case 6:
                            streamingWorld.TeleportToCoordinates(254, 408, StreamingWorld.RepositionMethods.RandomStartMarker);
                            return("Teleported player to Pothago/The Stronghold of Cirden");

                        case 7:
                            streamingWorld.TeleportToCoordinates(109, 158, StreamingWorld.RepositionMethods.RandomStartMarker);
                            return("Teleported player to Daggerfall/Privateer's Hold");

                        case 8:
                            streamingWorld.TeleportToCoordinates(860, 245, StreamingWorld.RepositionMethods.RandomStartMarker);
                            return("Teleported player to Wayrest/Merwark Hollow");

                        case 9:
                            streamingWorld.TeleportToCoordinates(718, 204, StreamingWorld.RepositionMethods.RandomStartMarker);
                            return("Teleported player to Isle of Balfiera/Direnni Tower");

                        default:
                            break;
                        }

                        return("Teleported successfully.");
                    }
                }

                return("Invalid location index");
            }
示例#22
0
 public Help(object source, HelpCommand helpCommand)
 {
     Source          = source;
     RootHelpCommand = helpCommand;
 }
示例#23
0
        static void Main(string[] args)
        {
            var settings = new JsonSettingsReader();

            if (args.Length == 0)
            {
                settings.Read("settings.debug.json");
            }
            else
            {
                settings.Read(args[0]);
            }

            TimeUtils.Initialize(settings.Timezones);

            var kernel = new StandardKernel();

            kernel.Bind <ILoggerFactory>().To <ConsoleLoggerFactory>();
            kernel.Bind <ISettingsManager>().ToConstant(settings);

            // I18N
            ICatalog catalog;

            if (string.IsNullOrEmpty(settings.Language))
            {
                catalog = new Catalog("raidbot", "i18n", new CultureInfo("en-US"));
            }
            else
            {
                catalog = new Catalog("raidbot", "i18n", new CultureInfo(settings.Language));
            }
            kernel.Bind <ICatalog>().ToConstant(catalog);
            kernel.Bind <ITimeService>().To <TimeService>();

            // Core services
            var database = kernel.Get <Database>();

            database.Setup(settings.DataFolder);
            kernel.Bind <IDatabase>().ToConstant(database);
            kernel.Bind <IPrivateConversationManager>().To <PrivateConversationManager>().InSingletonScope();

            // Google location API
            var googleLocationAPIService = kernel.Get <GoogleAddressService>();

            googleLocationAPIService.SetApiKey(settings.GoogleLocationAPIKey);
            kernel.Bind <ILocationToAddressService>().ToConstant(googleLocationAPIService);

            // Set up the messaging client
            CancellationTokenSource source = new CancellationTokenSource();
            TelegramClient          client = kernel.Get <ThrottlingTelegramClient>();

            client.Setup(settings.BotKey, source.Token);
            kernel.Bind <IMessagingClient>().ToConstant(client);

            // Set up the console commands
            var helpCommand = new HelpCommand();

            kernel.Bind <IConsoleCommand>().To <PingCommand>().InSingletonScope();
            kernel.Bind <IConsoleCommand>().To <HelpCommand>().InSingletonScope();
            kernel.Bind <IConsoleCommand>().To <LogLevelCommand>().InSingletonScope();
            kernel.Bind <IConsoleCommand>().ToConstant(new ConsoleCommands.ListCommand {
            }).InSingletonScope();
            kernel.Bind <IConsoleCommand>().ToConstant(new ConsoleCommands.UpdateCommand {
            }).InSingletonScope();
            kernel.Bind <IConsoleCommand>().ToConstant(new ConsoleCommands.ExitCommand {
                TokenSource = source
            }).InSingletonScope();
            kernel.Bind <IConsoleCommand>().To <ConsoleCommands.MeCommand>().InSingletonScope();

            // Set up the components
            kernel.Bind <IBotModule>().To <Modules.RaidCreationWizard>().InSingletonScope();
            kernel.Bind <IBotModule>().To <Modules.RaidEditor>().InSingletonScope();
            kernel.Bind <IBotModule>().To <Modules.RaidEventHandler>().InSingletonScope();
            kernel.Bind <IBotModule>().To <Modules.CleanupChannel>().InSingletonScope();
            kernel.Bind <IBotModule>().To <Modules.UpdatePublishedRaidMessages>().InSingletonScope();
            kernel.Bind <IBotModule>().To <Modules.CreateRaidsFromPogoAfo>().InSingletonScope();
            kernel.Bind <IBotModule>().To <Modules.SummarizeActiveRaids>().InSingletonScope();

            kernel.Bind <IBotModule>().To <ChatCommands.WhoAmI>().InSingletonScope();
            kernel.Bind <IBotModule>().To <ChatCommands.WhereAmI>().InSingletonScope();
            kernel.Bind <IBotModule>().To <ChatCommands.RaidStatistics>().InSingletonScope();
            kernel.Bind <IBotModule>().To <ChatCommands.Alias>().InSingletonScope();
            kernel.Bind <IBotModule>().To <ChatCommands.Level>().InSingletonScope();

            var modules = kernel.GetAll <IBotModule>().ToList();

            // Start the system
            modules.ForEach(m => m.Startup());
            client.Start();

            // Runt the console loop in the background
            var consoleLoop = kernel.Get <ConsoleLoop>();

            consoleLoop.Run(source.Token);

            // Shut down the modules
            modules.ForEach(m => m.Shutdown());

            Console.WriteLine("Program terminated. Have a nice day.");
        }
示例#24
0
文件: Program.cs 项目: EkardNT/CS143B
 private static void On(HelpCommand command)
 {
     foreach (var builder in builders)
     {
         WriteHelp("- ");
         WriteHelpLine(builder.Usage);
         WriteHelp("\t");
         WriteHelpLine(builder.Description);
     }
 }
	public void SetCommand(HelpCommand helpcmd)
	{
		this._commandobj = helpcmd;
		
	} 
示例#26
0
        internal static int ProcessArgs(string[] args, ITelemetry telemetryClient = null)
        {
            // CommandLineApplication is a bit restrictive, so we parse things ourselves here. Individual apps should use CLA.

            var success = true;
            var command = string.Empty;
            var lastArg = 0;
            TopLevelCommandParserResult topLevelCommandParserResult = TopLevelCommandParserResult.Empty;

            using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel =
                       new FirstTimeUseNoticeSentinel())
            {
                IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel;
                IAspNetCertificateSentinel  aspNetCertificateSentinel  = new AspNetCertificateSentinel();
                IFileSentinel toolPathSentinel = new FileSentinel(
                    new FilePath(
                        Path.Combine(
                            CliFolderPathCalculator.DotnetUserProfileFolderPath,
                            ToolPathSentinelFileName)));

                for (; lastArg < args.Length; lastArg++)
                {
                    if (IsArg(args[lastArg], "d", "diagnostics"))
                    {
                        Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString);
                        CommandContext.SetVerbose(true);
                    }
                    else if (IsArg(args[lastArg], "version"))
                    {
                        PrintVersion();
                        return(0);
                    }
                    else if (IsArg(args[lastArg], "info"))
                    {
                        PrintInfo();
                        return(0);
                    }
                    else if (IsArg(args[lastArg], "h", "help") ||
                             args[lastArg] == "-?" ||
                             args[lastArg] == "/?")
                    {
                        HelpCommand.PrintHelp();
                        return(0);
                    }
                    else if (args[lastArg].StartsWith("-", StringComparison.OrdinalIgnoreCase))
                    {
                        Reporter.Error.WriteLine($"Unknown option: {args[lastArg]}");
                        success = false;
                    }
                    else
                    {
                        // It's the command, and we're done!
                        command = args[lastArg];
                        if (string.IsNullOrEmpty(command))
                        {
                            command = "help";
                        }

                        var environmentProvider = new EnvironmentProvider();

                        bool generateAspNetCertificate =
                            environmentProvider.GetEnvironmentVariableAsBool("DOTNET_GENERATE_ASPNET_CERTIFICATE", true);
                        bool skipFirstRunExperience =
                            environmentProvider.GetEnvironmentVariableAsBool("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", false);
                        bool telemetryOptout =
                            environmentProvider.GetEnvironmentVariableAsBool("DOTNET_CLI_TELEMETRY_OPTOUT", false);

                        ReportDotnetHomeUsage(environmentProvider);

                        topLevelCommandParserResult = new TopLevelCommandParserResult(command);
                        var hasSuperUserAccess = false;
                        if (IsDotnetBeingInvokedFromNativeInstaller(topLevelCommandParserResult))
                        {
                            aspNetCertificateSentinel  = new NoOpAspNetCertificateSentinel();
                            firstTimeUseNoticeSentinel = new NoOpFirstTimeUseNoticeSentinel();
                            toolPathSentinel           = new NoOpFileSentinel(exists: false);
                            hasSuperUserAccess         = true;

                            // When running through a native installer, we want the cache expansion to happen, so
                            // we need to override this.
                            skipFirstRunExperience = false;
                        }

                        var dotnetFirstRunConfiguration = new DotnetFirstRunConfiguration(
                            generateAspNetCertificate: generateAspNetCertificate,
                            skipFirstRunExperience: skipFirstRunExperience,
                            telemetryOptout: telemetryOptout);

                        ConfigureDotNetForFirstTimeUse(
                            firstTimeUseNoticeSentinel,
                            aspNetCertificateSentinel,
                            toolPathSentinel,
                            hasSuperUserAccess,
                            dotnetFirstRunConfiguration,
                            environmentProvider);

                        break;
                    }
                }
                if (!success)
                {
                    HelpCommand.PrintHelp();
                    return(1);
                }

                if (telemetryClient == null)
                {
                    telemetryClient = new Telemetry.Telemetry(firstTimeUseNoticeSentinel);
                }
                TelemetryEventEntry.Subscribe(telemetryClient.TrackEvent);
                TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);
            }

            IEnumerable <string> appArgs =
                (lastArg + 1) >= args.Length
                ? Enumerable.Empty <string>()
                : args.Skip(lastArg + 1).ToArray();

            if (CommandContext.IsVerbose())
            {
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }

            TelemetryEventEntry.SendFiltered(topLevelCommandParserResult);

            int exitCode;

            if (BuiltInCommandsCatalog.Commands.TryGetValue(topLevelCommandParserResult.Command, out var builtIn))
            {
                var parseResult = Parser.Instance.ParseFrom($"dotnet {topLevelCommandParserResult.Command}", appArgs.ToArray());
                if (!parseResult.Errors.Any())
                {
                    TelemetryEventEntry.SendFiltered(parseResult);
                }

                exitCode = builtIn.Command(appArgs.ToArray());
            }
            else
            {
                CommandResult result = CommandFactoryUsingResolver.Create(
                    "dotnet-" + topLevelCommandParserResult.Command,
                    appArgs,
                    FrameworkConstants.CommonFrameworks.NetStandardApp15)
                                       .Execute();
                exitCode = result.ExitCode;
            }

            telemetryClient.Flush();
            return(exitCode);
        }
示例#27
0
        internal static int ProcessArgs(string[] args, ITelemetry telemetryClient = null)
        {
            var parseResult = Parser.Instance.Parse(args);

            using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel =
                       new FirstTimeUseNoticeSentinel())
            {
                IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel;
                IAspNetCertificateSentinel  aspNetCertificateSentinel  = new AspNetCertificateSentinel();
                IFileSentinel toolPathSentinel = new FileSentinel(
                    new FilePath(
                        Path.Combine(
                            CliFolderPathCalculator.DotnetUserProfileFolderPath,
                            ToolPathSentinelFileName)));
                if (parseResult.ValueForOption <bool>(Parser.DiagOption))
                {
                    Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString);
                    CommandContext.SetVerbose(true);
                    Reporter.Reset();
                }
                if (parseResult.HasOption(Parser.VersionOption))
                {
                    CommandLineInfo.PrintVersion();
                    return(0);
                }
                else if (parseResult.HasOption(Parser.InfoOption))
                {
                    CommandLineInfo.PrintInfo();
                    return(0);
                }
                else if (parseResult.CommandResult.Command.Equals(Parser.RootCommand) && parseResult.HasOption("-h"))
                {
                    HelpCommand.PrintHelp();
                    return(0);
                }
                else if (parseResult.Directives.Count() > 0)
                {
                    return(parseResult.Invoke());
                }
                else
                {
                    PerformanceLogEventSource.Log.FirstTimeConfigurationStart();

                    var environmentProvider = new EnvironmentProvider();

                    bool generateAspNetCertificate =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_GENERATE_ASPNET_CERTIFICATE", defaultValue: true);
                    bool telemetryOptout =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_CLI_TELEMETRY_OPTOUT", defaultValue: false);
                    bool addGlobalToolsToPath =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", defaultValue: true);
                    bool nologo =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_NOLOGO", defaultValue: false);

                    ReportDotnetHomeUsage(environmentProvider);

                    var isDotnetBeingInvokedFromNativeInstaller = false;
                    if (parseResult.CommandResult.Command.Name.Equals(Parser.InstallSuccessCommand.Name))
                    {
                        aspNetCertificateSentinel  = new NoOpAspNetCertificateSentinel();
                        firstTimeUseNoticeSentinel = new NoOpFirstTimeUseNoticeSentinel();
                        toolPathSentinel           = new NoOpFileSentinel(exists: false);
                        isDotnetBeingInvokedFromNativeInstaller = true;
                    }

                    var dotnetFirstRunConfiguration = new DotnetFirstRunConfiguration(
                        generateAspNetCertificate: generateAspNetCertificate,
                        telemetryOptout: telemetryOptout,
                        addGlobalToolsToPath: addGlobalToolsToPath,
                        nologo: nologo);

                    ConfigureDotNetForFirstTimeUse(
                        firstTimeUseNoticeSentinel,
                        aspNetCertificateSentinel,
                        toolPathSentinel,
                        isDotnetBeingInvokedFromNativeInstaller,
                        dotnetFirstRunConfiguration,
                        environmentProvider);
                    PerformanceLogEventSource.Log.FirstTimeConfigurationStop();
                }

                PerformanceLogEventSource.Log.TelemetryRegistrationStart();

                if (telemetryClient == null)
                {
                    telemetryClient = new Telemetry.Telemetry(firstTimeUseNoticeSentinel);
                }
                TelemetryEventEntry.Subscribe(telemetryClient.TrackEvent);
                TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);

                PerformanceLogEventSource.Log.TelemetryRegistrationStop();
            }

            if (CommandContext.IsVerbose())
            {
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }
            PerformanceLogEventSource.Log.TelemetrySaveIfEnabledStart();
            TelemetryEventEntry.SendFiltered(parseResult);
            PerformanceLogEventSource.Log.TelemetrySaveIfEnabledStop();

            var topLevelCommands = new string[] { "dotnet", parseResult.RootSubCommandResult() }.Concat(Parser.DiagOption.Aliases);
            int exitCode;

            if (parseResult.CommandResult.Command.Name.Equals("dotnet") && string.IsNullOrEmpty(parseResult.ValueForArgument <string>(Parser.DotnetSubCommand)))
            {
                exitCode = 0;
            }
            else if (BuiltInCommandsCatalog.Commands.TryGetValue(parseResult.RootSubCommandResult(), out var builtIn))
            {
                PerformanceLogEventSource.Log.BuiltInCommandParserStart();
                if (parseResult.Errors.Count <= 0)
                {
                    PerformanceLogEventSource.Log.TelemetrySaveIfEnabledStart();
                    TelemetryEventEntry.SendFiltered(parseResult);
                    PerformanceLogEventSource.Log.TelemetrySaveIfEnabledStop();
                }

                PerformanceLogEventSource.Log.BuiltInCommandStart();

                exitCode = builtIn.Command(args.Where(t => !topLevelCommands.Contains(t)).ToArray());
                PerformanceLogEventSource.Log.BuiltInCommandStop();
            }
            else
            {
                PerformanceLogEventSource.Log.ExtensibleCommandResolverStart();
                var resolvedCommand = CommandFactoryUsingResolver.Create(
                    "dotnet-" + parseResult.ValueForArgument <string>(Parser.DotnetSubCommand),
                    args.Where(t => !topLevelCommands.Contains(t)).ToArray(),
                    FrameworkConstants.CommonFrameworks.NetStandardApp15);
                PerformanceLogEventSource.Log.ExtensibleCommandResolverStop();

                PerformanceLogEventSource.Log.ExtensibleCommandStart();
                var result = resolvedCommand.Execute();
                PerformanceLogEventSource.Log.ExtensibleCommandStop();

                exitCode = result.ExitCode;
            }

            PerformanceLogEventSource.Log.TelemetryClientFlushStart();
            telemetryClient.Flush();
            PerformanceLogEventSource.Log.TelemetryClientFlushStop();

            return(exitCode);
        }
示例#28
0
 private void _helpButton_Clicked(object sender, EventArgs e)
 {
     HelpCommand?.Execute(null);
 }
示例#29
0
 static public void Add(HelpCommand helpFunc)
 {
     helpDelegate += helpFunc;
 }