public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { if (args.Count != 1) return CommandResultCode.SyntaxError; PropertyRegistry properties = Properties; if (properties == null) { Application.Error.WriteLine("the current context does not support properties."); return CommandResultCode.ExecutionFailed; } if (!args.MoveNext()) return CommandResultCode.SyntaxError; String name = args.Current; PropertyHolder holder = properties.GetProperty(name); if (holder == null) return CommandResultCode.ExecutionFailed; string defaultValue = holder.DefaultValue; try { properties.SetProperty(name, defaultValue); } catch (Exception) { Application.Error.WriteLine("setting to default '" + defaultValue + "' failed."); return CommandResultCode.ExecutionFailed; } return CommandResultCode.Success; }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { PropertyRegistry properties = Properties; if (properties == null) { Application.Error.WriteLine("the current context does not support properties."); return CommandResultCode.ExecutionFailed; } if (args.MoveNext()) { string name = args.Current; PropertyHolder holder = properties.GetProperty(name); if (holder == null) return CommandResultCode.ExecutionFailed; PrintDescription(name, holder, Application.Error); return CommandResultCode.Success; } ProperiesColumns[0].ResetWidth(); ProperiesColumns[1].ResetWidth(); TableRenderer table = new TableRenderer(ProperiesColumns, Application.Out); foreach(KeyValuePair<string, PropertyHolder> entry in properties) { ColumnValue[] row = new ColumnValue[3]; PropertyHolder holder = entry.Value; row[0] = new ColumnValue(entry.Key); row[1] = new ColumnValue(holder.Value); row[2] = new ColumnValue(holder.ShortDescription); table.AddRow(row); } table.CloseTable(); return CommandResultCode.Success; }
public void Execute(CommandArguments args) { var op = args.NextString(string.Empty); switch (op.ToLower()) { case "start": var fileName = args.NextString(); try { Logger.LogOutput = new StreamWriter(fileName, true); } catch (Exception ex) { Logger.WriteErrorLine("Could not open log file {0}: {1}", fileName, ex.Message); } return; case "stop": Logger.LogOutput.Dispose(); Logger.LogOutput = null; return; } Logger.WriteErrorLine("Unknown log operation: {0}", op); }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { if (!args.MoveNext()) return CommandResultCode.SyntaxError; string alias = args.Current; // no quoted aliases.. if (alias.StartsWith("\"") || alias.StartsWith("'")) return CommandResultCode.SyntaxError; // unless we override an alias, moan, if this command already // exists. if (!Application.Commands.Aliases.HasAlias(alias) && Application.Commands.ContainsCommand(alias)) { Error.WriteLine("cannot alias built-in command!"); return CommandResultCode.ExecutionFailed; } if (!args.MoveNext()) return CommandResultCode.SyntaxError; String value = StripQuotes(args.Current); // rest of values. Application.Commands.Aliases.AddAlias(alias, value); return CommandResultCode.Success; }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { ISettingsHandler handler = Application as ISettingsHandler; if (handler == null) { Error.WriteLine("The application doesn't support settings."); return CommandResultCode.ExecutionFailed; } if (args.MoveNext()) return CommandResultCode.SyntaxError; VarColumns[0].ResetWidth(); VarColumns[1].ResetWidth(); TableRenderer table = new TableRenderer(VarColumns, Out); table.EnableHeader = true; table.EnableFooter = true; foreach(KeyValuePair<string, string> setting in handler.Settings) { if (setting.Key == ApplicationSettings.SpecialLastCommand) continue; ColumnValue[] row = new ColumnValue[4]; row[0] = new ColumnValue(setting.Key); row[1] = new ColumnValue(setting.Value); table.AddRow(row); } table.CloseTable(); Error.WriteLine(); return CommandResultCode.Success; }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { if (context == null) return CommandResultCode.ExecutionFailed; NetworkContext networkContext = (NetworkContext)context; if (!args.MoveNext()) return CommandResultCode.SyntaxError; if (args.Current == "analytics") { } else if (args.Current == "free") { } else if (args.Current == "network") { ShowNetwork(networkContext); return CommandResultCode.Success; } else if (args.Current == "paths") { return ShowPaths(networkContext); } else if (args.Current == "status") { ShowStatus(networkContext); return CommandResultCode.Success; } else { return CommandResultCode.SyntaxError; } return CommandResultCode.ExecutionFailed; }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { NetworkContext networkContext = (NetworkContext) context; if (!args.MoveNext()) return CommandResultCode.SyntaxError; if (args.Current != "block") return CommandResultCode.SyntaxError; if (!args.MoveNext()) return CommandResultCode.SyntaxError; if (args.Current != "availability" && args.Current != "avail") return CommandResultCode.SyntaxError; try { Random r = new Random(); BlockMapProcess(networkContext, new BlockMapProcessImpl(this, networkContext, r)); } catch(Exception e) { Error.WriteLine("unable to fix block availability: " + e.Message); return CommandResultCode.ExecutionFailed; } return CommandResultCode.Success; }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { if (!args.MoveNext()) { ProductInfo product = ProductInfo.Current; StringWriter writer = new StringWriter(); writer.WriteLine("---------------------------------------------------------------------------"); writer.WriteLine(" {0} {1} {2}", product.Title, product.Version, product.Copyright); writer.WriteLine(); writer.WriteLine(" CloudB Admin is provided AS IS and comes with ABSOLUTELY NO WARRANTY"); writer.WriteLine(" This is free software, and you are welcome to redistribute it under the"); writer.WriteLine(" conditions of the Lesser GNU Public License."); writer.WriteLine("---------------------------------------------------------------------------"); Out.Write(writer.ToString()); return CommandResultCode.Success; } if (args.Current == "version") { //TODO: } else if (args.Current == "license") { Out.WriteLine("Lesser GNU Public License <http://www.gnu.org/licenses/lgpl.txt>"); return CommandResultCode.Success; } return CommandResultCode.SyntaxError; }
static int Main(string[] args) { try { var arg = new CommandArguments(args); var fileSystem = arg.FileSystem; string cd = fileSystem.Directory.GetCurrentDirectory(); string path = Path.Combine(cd, arg.Path); var info = new FileInfo(path); DirectoryInfoBase parent = fileSystem.DirectoryInfo.FromDirectoryName(info.Directory.FullName); FileSystemInfoBase file = parent.GetFileSystemInfos().Where(f => f.Name == info.Name).FirstOrDefault(); if (file == null) { throw new FileNotFoundException(info.FullName + " does not exists."); } else if (file is DirectoryInfoBase) { throw new NotSupportedException("Delete directory is not supported."); } file.Delete(); return 0; } catch (Exception ex) { Console.WriteLine(ex); return -1; } }
public override void OnCommand(CommandArguments command) { var count = PICSProductInfo.ProcessedSubs.Count; if (count > 100) { CommandHandler.ReplyToCommand(command, "There are currently {0} packages awaiting to be processed, try again later.", count); return; } uint subID; if (command.Message.Length > 0 && uint.TryParse(command.Message, out subID)) { JobManager.AddJob(() => Steam.Instance.Apps.PICSGetProductInfo(null, subID, false, false), new JobManager.IRCRequest { Target = subID, Type = JobManager.IRCRequestType.TYPE_SUB, Command = command }); return; } CommandHandler.ReplyToCommand(command, "Usage:{0} sub <subid>", Colors.OLIVE); }
public override bool Execute(CommandArguments args, IPermissible sender) { var commands = CommandManager.Instance.GetCommands(); foreach (var cmd in commands.Values.Distinct()) { var perm = cmd.RequiredPermission; if (sender != null && perm != null && !sender.HasPermission(perm)) continue; var cmd1 = cmd; var triggers = commands.Where(x => x.Value == cmd1).Select(x => x.Key).ToList(); var count = triggers.Count; for (var i = 0; i < count; i++) { Console.Write(triggers[i]); if (i < count - 1) Console.Write("|"); } Console.WriteLine(": {0}", cmd.Description); } return true; }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { if (args.MoveNext()) return CommandResultCode.SyntaxError; NetworkContext networkContext = context as NetworkContext; if (networkContext == null) return CommandResultCode.ExecutionFailed; Out.WriteLine(); Out.WriteLine("refreshing..."); Out.Flush(); networkContext.Network.Refresh(); try { //TODO: // networkContext.Network.Configuration.Reload(); } catch (IOException e) { Error.WriteLine("Unable to refresh network config due to IO error"); Error.WriteLine(e.Message); Error.WriteLine(e.StackTrace); } Out.WriteLine("done."); Out.WriteLine(); return CommandResultCode.Success; }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { if (!args.MoveNext()) return CommandResultCode.SyntaxError; if (!args.Current.Equals("path")) return CommandResultCode.SyntaxError; if (!args.MoveNext()) return CommandResultCode.SyntaxError; string pathName = args.Current; NetworkContext networkContext = (NetworkContext) context; PathInfo pathInfo = networkContext.Network.GetPathInfo(pathName); if (pathInfo == null) { Out.WriteLine("The path '" + pathName + "' was not found."); return CommandResultCode.ExecutionFailed; } IServiceAddress address = pathInfo.RootLeader; Out.Write("Root " + address); Out.WriteLine(" is managing path " + pathName); Out.Flush(); return CommandResultCode.Success; }
public override bool Execute(CommandArguments args, IPermissible sender) { var name = args.NextString(); if (string.IsNullOrEmpty(name)) return false; if (name.Length < AccountManager.MinNameLength || name.Length > AccountManager.MaxNameLength) return false; var password = args.NextString(); if (string.IsNullOrEmpty(password)) return false; if (password.Length < AccountManager.MinPasswordLength || password.Length > AccountManager.MaxPasswordLength) return false; var email = args.NextString(); if (string.IsNullOrEmpty(email)) return false; var box = args.NextEnum<ClientBoxLevel>() ?? ClientBoxLevel.Cataclysm; var locale = args.NextEnum<ClientLocale>() ?? ClientLocale.English; AccountManager.Instance.CreateAccount(name, password, email, box, locale); return true; }
public void Execute(CommandArguments args) { var expr = args.NextString(); var backtrace = SoftDebugger.Backtrace; if (backtrace == null) { Logger.WriteErrorLine("No backtrace available."); return; } var frame = backtrace.CurrentStackFrame; if (frame == null) { Logger.WriteErrorLine("No stack frame available."); return; } try { var result = frame.GetExpressionValue(expr, true); Logger.WriteInfoLine("[{0}] {1}", result.TypeName, result.DisplayValue); } catch (Exception) { Logger.WriteErrorLine("Error in expression."); } }
public override void Execute(CommandArguments args, ICommandUser sender) { Console.WriteLine("Executing this command will permanently drop the entire database. Continue? (Y/N)"); var answer = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture).ToCharArray().FirstOrDefault(); if (answer == 'Y') AccountApplication.Instance.AccountDbContext.PostAsync(x => x.Schema.Drop()); }
public void Execute(CommandArguments args) { if (SoftDebugger.State != DebuggerState.Null) SoftDebugger.Stop(); CommandLine.Stopped = true; Logger.WriteInfoLine("Bye!"); }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { int exitCode = 0; if (args.Count == 1) exitCode = Int32.Parse(args.Peek(0)); Application.Exit(exitCode); return CommandResultCode.Success; }
public void Execute(CommandArguments args) { if (SoftDebugger.State != DebuggerState.Null) { Logger.WriteErrorLine("A session is already active."); return; } SoftDebugger.InitializeSession(); }
public override bool Execute(CommandArguments args, IPermissible sender) { Console.WriteLine("Executing this command will permanently overwrite the entire database. Continue? (Y/N)"); var answer = Console.ReadLine().ToUpper().ToCharArray().SingleOrDefault(); if (answer == 'Y') AccountApplication.Instance.AccountDbContext.Post(x => x.Schema.Create()); return true; }
public override bool Execute(CommandArguments args, IPermissible sender) { var fileName = args.NextString(); if (string.IsNullOrEmpty(fileName)) return false; AccountApplication.Instance.AccountDbContext.Post(x => x.Schema.Export(fileName)); return true; }
public void Execute(CommandArguments args) { if (args.HasArguments) { var dir = args.NextString(); SoftDebugger.WorkingDirectory = dir; Logger.WriteInfoLine("Changed working directory: {0}", dir); } else Logger.WriteInfoLine("Current working directory: {0}", SoftDebugger.WorkingDirectory); }
public void Execute(CommandArguments args) { if (SoftDebugger.State == DebuggerState.Null) { Logger.WriteErrorLine("No session is active."); return; } SoftDebugger.Stop(); Logger.WriteInfoLine("Process stopped."); }
public override void ExecuteCommand(string name, CommandArguments parameters) { switch (name) { case SetMessageCommand: DoSetMessage(parameters.ReadParameter<string>()); break; default: MessageBox.Show("Unknown command: " + name); break; } }
public override void Execute(CommandArguments args, ICommandUser sender) { var fileName = args.NextString(); if (string.IsNullOrEmpty(fileName)) { sender.Respond("No file name given."); return; } AccountApplication.Instance.AccountDbContext.PostAsync(x => x.Schema.Export(fileName)); }
public override void OnCommand(CommandArguments command) { Steam.Instance.Client.Connect(); foreach (var idler in Application.GCIdlers) { idler.Client.Connect(); } CommandHandler.ReplyToCommand(command, "Reconnect forced."); }
private IEnumerable<string> filesFromArgument(CommandArguments args) { var filename = Path.GetFileName(args.File); var directory = Path.GetDirectoryName(args.File); if (!args.Recursive) return filesFromArgument(directory, filename); var files = new List<string>(); foreach (var dir in getDirectoriesRecursive(directory)) files.AddRange(filesFromArgument(dir, filename)); return files; }
protected override bool execute(CommandArguments arguments, StringBuilder output) { if (arguments.ContainsParameter("show")) { AppDomainController.Instance.ShowRef(arguments["show"].Values[0]); } else if (arguments.ContainsParameter("set") && arguments.ContainsParameter("value")) { AppDomainController.Instance.SetRef(arguments["set"].Values[0],arguments["value"].Values[0]); } return true; }
public void ValidateCommandArguments() { string fileName = Path.GetTempFileName(); fileName = fileName.Replace(Path.GetTempPath(), ""); CommandArguments cmdArgs = new CommandArguments(); Assert.IsNotNull(cmdArgs); cmdArgs = new CommandArguments(fileName); Assert.IsNotNull(cmdArgs); string[] args = { fileName, "Sum" }; cmdArgs = new CommandArguments(args); Assert.IsNotNull(cmdArgs); }
public void Execute(CommandArguments args) { var hasArgs = args.HasArguments; var lowerOffset = 0; var upperOffset = 0; if (hasArgs) { lowerOffset = args.NextInt32(); upperOffset = args.NextInt32(); if (upperOffset < 0) { Logger.WriteErrorLine("Invalid line count."); return; } } var backtrace = SoftDebugger.Backtrace; if (backtrace == null) { Logger.WriteErrorLine("No backtrace available."); return; } var frame = backtrace.CurrentStackFrame; if (frame == null) { Logger.WriteErrorLine("No stack frame available."); return; } if (hasArgs) upperOffset += System.Math.Abs(lowerOffset); var disasm = frame.Disassemble(hasArgs ? lowerOffset : -10, hasArgs ? upperOffset + 1 : 20); foreach (var line in disasm) { if (line.IsOutOfRange) continue; var str = string.Format("{0}:\t{1}", line.Address.ToString(Environment.Is64BitProcess ? "X8" : "X4"), line.Code); if (line.Address == frame.Address) Logger.WriteEmphasisLine("{0}", str); else Logger.WriteInfoLine("{0}", str); } }
/// <summary> /// Parse the incoming command /// </summary> /// <param name="command">command for paySlip</param> /// <param name="cmdArgs">returns command arguments</param> /// <returns></returns> private bool ParseCommand(string command, CommandArguments cmdArgs) { try { Command inputCommand; string paySlipCmd = string.Empty; string[] argDelimiter = command.Split(' '); //Check for valid command //Empty command or command with more than 2 string parts is invalid. It also checks spelling if (argDelimiter.Length > 0 && argDelimiter.Length < 3 && Enum.TryParse <Command>(argDelimiter[0], true, out inputCommand)) { cmdArgs.Instruction = inputCommand; } else { return(false); } //PLACE command without coordinates is invalid //non-PLACE command with extra characters/words is invalid if ((cmdArgs.Instruction.Equals(Command.PLACE) && argDelimiter.Length == 1) || (!cmdArgs.Instruction.Equals(Command.PLACE) && argDelimiter.Length == 2)) { return(false); } else if (cmdArgs.Instruction.Equals(Command.PLACE) && argDelimiter.Length == 2) { return(ParseArguments(argDelimiter[1], cmdArgs)); } return(true); } catch (Exception) { throw; } }
public void TestConstructAndRun() { const string inputFile = @"\TestUtils\HpcInput.txt"; const string outputFile = @"\TestUtils\results.txt"; string assemblypath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6); string inputFilePath = assemblypath + inputFile; FileInfo fileInfo = new FileInfo(assemblypath + outputFile); if (fileInfo.Exists) { fileInfo.Delete(); } string[] args = { "-InputFile", "InputFile((\"" + inputFilePath + "\"))", "-Operator", "Sum" }; CommandArguments.ConstructAndRun <AggregateNumbers>(args); FileStream fs = fileInfo.OpenRead(); byte[] buffer = new byte[2]; fs.Read(buffer, 0, 2); Assert.AreEqual(Encoding.ASCII.GetString(buffer), "15"); }
public CommandArguments Parse(string[] args) { _parsed = new CommandArguments(); _commandApp.HelpOption("-?|-h|--help"); #if NET462 _commandApp.Name = "flubu.exe"; #else _commandApp.Name = "dotnet flubu"; #endif _command = _commandApp.Argument("<Target> [build script arguments]", "The target to execute.", true); _scriptPath = _commandApp.Option("-s|--script <SCRIPT>", "Build script file to use.", CommandOptionType.SingleValue); _parallelTargetExecution = _commandApp.Option("--parallel", "If applied target's are executed in parallel", CommandOptionType.NoValue); _targetsToExecute = _commandApp.Option("-tte|--targetsToExecute <TARGETS_TO_EXECUTE>", "Target's that must be executed. Otherwise fails.", CommandOptionType.SingleValue); _isDebug = _commandApp.Option("-d|--debug", "Enable debug logging.", CommandOptionType.NoValue); _configurationFile = _commandApp.Option("-cf|--configurationFile", "Path to the Flubu json configuration file. If not specified configuration is read from flubusettings.json ", CommandOptionType.SingleValue); _assemblyDirectories = _commandApp.Option("-ass", "Directory to search assemblies to include automatically in script (Assemblies in subdirectories are also loaded). If not specified assemblies are loaded by default from FlubuLib directory.", CommandOptionType.MultipleValue); _noDependencies = _commandApp.Option("-nd||--nodeps", "If applied no target dependencies are executed.", CommandOptionType.NoValue); _dryRun = _commandApp.Option("--dryRun", "Performs a dry run.", CommandOptionType.NoValue); _noInteractive = _commandApp.Option("--noint", "Disables interactive mode for all task members. Default values are used instead", CommandOptionType.NoValue); _commandApp.ExtendedHelpText = " <Target> help Shows detailed help for specified target."; _commandApp.OnExecute(() => PrepareDefaultArguments()); if (args == null) { args = new string[0]; } _parsed.Help = true; _commandApp.Execute(args); return(_parsed); }
public static CronJob With(Guid?id = null, string name = null, bool enabled = true, string executable = null, IEnumerable <string> arguments = null, string cronExpression = null, TimeSpan?logWarningAfter = null, TimeSpan?logErrorAfter = null, TimeSpan?timeout = null, bool startImmediately = false, bool skipIfAlreadyRunning = false, bool stopIfApplicationStopping = true) { return(new CronJob { Id = id ?? Guid.NewGuid(), Name = name ?? Guid.NewGuid().ToString(), Enabled = enabled, Executable = executable ?? Guid.NewGuid().ToString(), Arguments = arguments ?? CommandArguments.CommandDurationInSeconds(0), CronExpression = cronExpression ?? CronExpression.Never, LogWarningAfter = logWarningAfter, LogErrorAfter = logErrorAfter, Timeout = timeout, StartImmediately = startImmediately, SkipIfAlreadyRunning = skipIfAlreadyRunning, StopIfApplicationStopping = stopIfApplicationStopping }); }
private void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs eventArgs) { var args = new string[eventArgs.CommandLine.Count]; eventArgs.CommandLine.CopyTo(args, 0); var commandLineArguments = new CommandArguments(args); if (commandLineArguments.ConsoleExit) { return; } var form = (MainForm)this.MainForm; if (commandLineArguments.HasArguments) { form.LoadDirectories(commandLineArguments); } else { form.RestoreFromTray(); } }
/// <summary> /// Processes. /// </summary> /// <param name="args">The command arguments.</param> /// <param name="context">The conversation context during the command processing.</param> /// <param name="cancellationToken">An optional cancellation token.</param> /// <returns>true if process succeeded; otherwise, false.</returns> async Task ICommandHandler.ProcessAsync(CommandArguments args, CommandConversationContext context, CancellationToken cancellationToken) { if (IsDisabled) { return; } try { await OnProcessAsync(args, context, cancellationToken); } catch (Exception ex) { var exConverted = ExceptionHandler.GetException(ex); if (exConverted == null) { return; } if (exConverted == ex) { throw; } throw exConverted; } }
public void OnStart(ApplicationHost onwer, CommandArguments args) { MemberShip.RegisterSignUpListener(this.MemberShip_OnSignUp); MemberShip.RegisterSignInListener(this.MemberShip_OnSignIn); }
static void Main(string[] args) { CommandArguments.ConstructAndRun <AggregateNumbers>(args); }
/// <summary> /// Provides a common function that all commands can implement that we can invoke generically /// </summary> /// <param name="commandArgument"></param> public virtual void Invoke(CommandArguments commandArgument) { }
public TextCommand(string Text) { this.Text = Text; Arguments = new CommandArguments(stream(new CommandArgument(nameof(Text), Text))); }
public void Execute(CommandArguments arguments) { XlsxManager.CurrentXlsx.CopySelectionToClipboard(); }
public override void Run(Configuration config, CommandArguments args) { base.Run(config, args); InterateWindowsClassicProject(config, GetProjectTargetDirectory(config, args.GetTarget(this))); }
public TargetTree(IServiceProvider provider, CommandArguments args) { _args = args; _provider = provider; }
public virtual GenericResult ValidateArguments(CommandArguments args) => new GenericResult().Valid();
public override void OnCommand(CommandArguments command) { Steam.Instance.Client.Connect(); }
/// <summary> /// Initialize the data needed for the GUI to run. /// </summary> /// <param name="argArray">The command line arguments.</param> public void Initialize(string[] argArray) { // Restore the component definitions. Must be done first so that components used // in designs can be linked to when loading the .intel file. try { AllComponents allComponents = new AllComponents(); } catch { Report.FatalError("Could not restore component definition file."); } // Need to identify the RaceName so we can load the correct race's intel. // We also want to identify the ClientState data store, if any, so we // can load it and use any historical information in there. // Last resort we will ask the user what to open. // There are a number of starting scenarios: // 1. the Nova GUI was started directly (e.g. in the debugger). // There will be zero options/arguments in the argArray. // We will continue an existing game, if any. // - get GameFolder from the config file // - look for races and ask the user to pick one. If none need to // ask the user to open a game (.intel), then treat as per option 2. // - Build the stateFileName from the GameFolder and Race name and // load it, if it exists. If not don't care. // 2. the Nova GUI was started from Nova Launcher's "open a game option". // or by double clicking a race in the Nova Console // There will be a .intel file listed in the argArray. // Evenything we need should be found in there. // 3. the Nova GUI was started from the launcher to continue a game. // There will be a StateFileName in the argArray. // Directly load the state file. If it is missing - FatalError. // (The race name and game folder will be loaded from the state file) StatePathName = null; string intelFileName = null; // process the arguments CommandArguments commandArguments = new CommandArguments(argArray); if (commandArguments.Contains(CommandArguments.Option.RaceName)) { EmpireState.Race.Name = commandArguments[CommandArguments.Option.RaceName]; } if (commandArguments.Contains(CommandArguments.Option.StateFileName)) { StatePathName = commandArguments[CommandArguments.Option.StateFileName]; } if (commandArguments.Contains(CommandArguments.Option.IntelFileName)) { intelFileName = commandArguments[CommandArguments.Option.IntelFileName]; } // Get the name of the folder where all the game files will be stored. // Normally this would be placed in the config file by the NewGame wizard. // We also cache a copy in the ClientState.Data.GameFolder GameFolder = FileSearcher.GetFolder(Global.ServerFolderKey, Global.ServerFolderName); if (GameFolder == null) { Report.FatalError("ClientState.cs Initialize() - An expected config file entry is missing\n" + "Have you ran the Race Designer and \n" + "Nova Console?"); } // Sort out what we need to initialize the ClientState bool isLoaded = false; // 1. the Nova GUI was started directly (e.g. in the debugger). // There will be zero options/arguments in the argArray. // We will continue an existing game, if any. if (argArray.Length == 0) { // - get GameFolder from the conf file - already done. // - look for races and ask the user to pick one. EmpireState.Race.Name = SelectRace(GameFolder); if (!string.IsNullOrEmpty(EmpireState.Race.Name)) { isLoaded = true; } else { // If none need to ask the user to open a game (.intel), // then treat as per option 2. try { OpenFileDialog fd = new OpenFileDialog(); fd.Title = "Open Game"; fd.FileName = "*." + Global.IntelExtension; DialogResult result = fd.ShowDialog(); if (result != DialogResult.OK) { Report.FatalError("ClientState.cs Initialize() - Open Game dialog canceled. Exiting. Try running the NovaLauncher."); } intelFileName = fd.FileName; } catch { Report.FatalError("ClientState.cs Initialize() - Unable to open a game. Try running the NovaLauncher."); } } } // 2. the Nova GUI was started from the launcher open a game option. // There will be a .intel file listed in the argArray. if (!isLoaded && intelFileName != null) { if (File.Exists(intelFileName)) { // Evenything we need should be found in there. IntelReader intelReader = new IntelReader(this); intelReader.ReadIntel(intelFileName); isLoaded = true; } else { Report.FatalError("ClientState.cs Initialize() - Could not locate .intel file \"" + intelFileName + "\"."); } } // 3. the Nova GUI was started from the launcher to continue a game. // There will be a StateFileName in the argArray. // NB: we already copied it to ClientState.Data.StateFileName, but other // code sets that too, so check the arguments to see if it was there. if (!isLoaded && commandArguments.Contains(CommandArguments.Option.StateFileName)) { // The state file is not sufficient to load a turn. We need the .intel // for this race. What race? The state file can tell us. // (i.e. The race name and game folder will be loaded from the state file) // If it is missing - FatalError. if (File.Exists(StatePathName)) { Restore(); IntelReader intelReader = new IntelReader(this); intelReader.ReadIntel(intelFileName); isLoaded = true; } else { Report.FatalError("ClientState.cs Initialize() - File not found. Could not continue game \"" + StatePathName + "\"."); } } if (!isLoaded) { Report.FatalError("ClientState.cs initialize() - Failed to find any .intel when initializing turn"); } FirstTurn = false; }
/// <summary> /// Main method /// Sample args :-InputFile InputFile("(C:\Temp\hpc.fasta)") /// Sample args with distribute: -Distribute OnHpcAndWait(MSR-L25-DEV29,26,Priority:AboveNormal,IsExclusive:True) -InputFile InputFile("(\\MSR-L25-DEV29\scratch\Bio.HPC\hpc.fasta)") /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine(SplashString()); CommandArguments.ConstructAndRun <SequenceContent>(args); }
public void OnStop(ApplicationHost onwer, CommandArguments args) { //empty action }
public override void OnInvoke(CommandInvoker invoker, CommandArguments args) { invoker.GetProcessor().ExitProcessor(); //Terminates the current processor. }
public void RunNullLoggerTest() { Program.Run(null, CommandArguments.Parse("Input.cs")); }
public abstract EvaluationResult Evaluate(IDatabase database, CommandArguments args);
/// <summary> /// Arranges using the specified args and logger. /// </summary> /// <param name="logger">The logger.</param> /// <param name="args">The command args.</param> /// <returns>True if succesful, otherwise false.</returns> private bool Arrange(TestLogger logger, params string[] args) { CommandArguments commandArgs = CommandArguments.Parse(args); return(Program.Run(logger, commandArgs)); }
private async Task <IBuildScript> SimpleFlubuInteractiveMode(IBuildScript script) { do { try { var flubuConsole = new FlubuConsole(_flubuSession.TargetTree, new List <Hint>()); var commandLine = flubuConsole.ReadLine(Directory.GetCurrentDirectory()); if (string.IsNullOrEmpty(commandLine)) { continue; } var splitedLine = commandLine.Split(' ').ToList(); if (_interactiveExitOnlyCommands.Contains(splitedLine[0], StringComparer.OrdinalIgnoreCase)) { break; } var app = new CommandLineApplication(false); IFlubuCommandParser parser = new FlubuCommandParser(app, null); var args = parser.Parse(commandLine.Split(' ') .Where(x => !string.IsNullOrWhiteSpace(x)) .Select(x => x.Trim()).ToArray()); _flubuSession.InteractiveArgs = args; _flubuSession.ScriptArgs = args.ScriptArguments; _args = args; var internalCommandExecuted = flubuConsole.ExecuteInternalCommand(commandLine); if (internalCommandExecuted) { continue; } if (!ReloadCommands.Contains(splitedLine[0], StringComparer.OrdinalIgnoreCase)) { var command = splitedLine.First(); var runProgram = _flubuSession.Tasks().RunProgramTask(command).DoNotLogTaskExecutionInfo() .WorkingFolder("."); splitedLine.RemoveAt(0); try { runProgram.WithArguments(splitedLine.ToArray()).Execute(_flubuSession); } catch (CommandUnknownException) { _flubuSession.LogError($"'{command}' is not recognized as a internal or external command, operable program or batch file."); } catch (TaskExecutionException) { } catch (ArgumentException) { } catch (Win32Exception) { } } else { script = await _scriptLoader.FindAndCreateBuildScriptInstanceAsync(_flubuSession.InteractiveArgs); } } catch (BuildScriptLocatorException) { } }while (script == null); return(script); }
private async Task <RoleConfig> CreateTempRole(CommandArguments e, ServerContext dbContext) { if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles) { await e.Message.Channel.SendMessageSafe(ErrorPermissionsString); return(null); } if (string.IsNullOrEmpty(e.TrimmedMessage)) { await e.SendReplySafe("What role? Name? Do you want me to come up with something silly or what? And when do you want to nuke it?"); return(null); } if (e.MessageArgs.Length != 2) { await e.SendReplySafe(e.Command.Description); return(null); } int durationHours = 0; try { Match dayMatch = Regex.Match(e.MessageArgs[1], "\\d+d", RegexOptions.IgnoreCase); Match hourMatch = Regex.Match(e.MessageArgs[1], "\\d+h", RegexOptions.IgnoreCase); if (!hourMatch.Success && !dayMatch.Success) { await e.SendReplySafe(e.Command.Description); dbContext.Dispose(); return(null); } if (hourMatch.Success) { durationHours = int.Parse(hourMatch.Value.Trim('h').Trim('H')); } if (dayMatch.Success) { durationHours += 24 * int.Parse(dayMatch.Value.Trim('d').Trim('D')); } } catch (Exception) { await e.SendReplySafe(e.Command.Description); dbContext.Dispose(); return(null); } RoleConfig roleConfig = null; string response = Localisation.SystemStrings.DiscordShitEmoji; try { RestRole role = await e.Server.Guild.CreateRoleAsync(e.MessageArgs[0], GuildPermissions.None); roleConfig = dbContext.GetOrAddRole(e.Server.Id, role.Id); roleConfig.DeleteAtTime = DateTime.UtcNow + TimeSpan.FromHours(durationHours); response = $"Role created: `{role.Name}`\n Id: `{role.Id}`\n Delete at `{Utils.GetTimestamp(roleConfig.DeleteAtTime)}`"; } catch (Exception exception) { await this.HandleException(exception, "CreateTempRole failed.", e.Server.Id); } await e.SendReplySafe(response); return(roleConfig); }
public override CommandResultCode Execute(IExecutionContext context, CommandArguments args) { Error.WriteLine("Not Implemented"); return(CommandResultCode.ExecutionFailed); }
public void ParseInputBackupRestoreTest() { CommandArguments.Parse("Input.cs", "/b", "/r"); }
public override object CommandHandler(SocketMessage socketMessage, string input, CommandArguments arguments) { ApplyMode(arguments); ApplyPlayer(socketMessage.Author.Id, input); //List<OsuUser> users = APIHelper<List<OsuUser>>.GetData(apiUrl + "get_user?u&k="+apiKey+"&u=" + username); if (_osuUser == null) { return("No user has been found."); } else { EmbedFieldBuilder topplayField = new EmbedFieldBuilder { Name = "Top plays", Value = "No top plays available", IsInline = false }; List <OsuPlay> topPlays = OsuApi.GetUserBest(_osuUser, _osuMode, 3, true); if (topPlays != null && topPlays.Count > 0) { string topPlayString = ""; int i = 0; topPlays.ForEach(play => { i++; string stringified = "**" + i + ". " + "[" + play.Beatmap.Title + " \\[" + play.Beatmap.DifficultyName + "\\]](https://osu.ppy.sh/beatmaps/" + play.Beatmap.BeatmapID + ") +" + ("" + ((OsuModsShort)play.Mods).ModParser() + "").Replace(", ", "") + "** (" + Mathf.Round(play.Beatmap.Starrating ?? 0, 1) + "\\*)\n" + OsuRanks.GetEmojiFromRank(play.Rank).ToString() + " • **" + Mathf.Round(play.Performance.CurrentValue).FormatNumber() + "pp** • " + Mathf.Round(play.Accuracy, 2) + "% • " + play.MaxCombo + (play.Beatmap.MaxCombo != null?"/" + play.Beatmap.MaxCombo:"x") + (play.IsFullcombo == "1" ? " FC" : "") + " • " + play.Score.FormatNumber() + "\n" + "Achieved " + DateTime.Parse(play.DateAchieved).Humanize(); topPlayString += stringified + "\n"; }); topplayField.Value = topPlayString; } EmbedBuilder embed = new EmbedBuilder() { Color = ParentManager.bot.BotColor, Title = "Profile of " + _osuUser.Name, ThumbnailUrl = "https://a.ppy.sh/" + _osuUser.ID, Description = "Showing osu!" + _osuMode + " statistics", Fields = new List <EmbedFieldBuilder>() { new EmbedFieldBuilder() { Name = "Rank", Value = _osuUser.Performance == 0 ? "No PP or inactive" : ("#" + _osuUser.Globalrank.FormatNumber() + " (:flag_" + _osuUser.CountryCode.ToLower() + ": #" + _osuUser.Countryrank.FormatNumber() + ")"), }, new EmbedFieldBuilder() { Name = "Performance", Value = Mathf.Round(_osuUser.Performance).FormatNumber() + "pp", IsInline = true }, new EmbedFieldBuilder() { Name = "Level", Value = Mathf.Floor(_osuUser.Level) + " (" + Mathf.Round((Mathf.Round(_osuUser.Level, 2) - Mathf.Floor(_osuUser.Level)) * 100) + "% to level " + (Mathf.Ceil(_osuUser.Level)) + ")", IsInline = true }, new EmbedFieldBuilder() { Name = "Ranked Score", Value = _osuUser.RankedScore.FormatNumber(), IsInline = true }, new EmbedFieldBuilder() { Name = "Playtime", Value = TimeSpan.FromSeconds(_osuUser.Playtime).Humanize(maxUnit: TimeUnit.Hour), IsInline = true }, new EmbedFieldBuilder() { Name = "Maps played", Value = _osuUser.Playcount.FormatNumber(), IsInline = true }, new EmbedFieldBuilder() { Name = "Total Score", Value = _osuUser.TotalScore.FormatNumber(), IsInline = true }, new EmbedFieldBuilder() { Name = "Ranks", Value = OsuRanks.GetEmojiFromRank("X") + " " + _osuUser.GetCountRankSS().FormatNumber() + " " + "• " + OsuRanks.GetEmojiFromRank("S") + " " + _osuUser.GetCountRankS().FormatNumber() + " " + "• " + OsuRanks.GetEmojiFromRank("A") + " " + _osuUser.GetCountRankA().FormatNumber(), IsInline = false }, topplayField }, Footer = new EmbedFooterBuilder() { Text = "User registered " + DateTime.Parse(_osuUser.Joindate).Humanize() } }; return(embed); } }
public void ParseInputConfigurationEmptyFlagTest() { CommandArguments.Parse("Input.cs", "/"); }
public CommandRunner(CommandFactory commandFactory, Configuration config, List <string> commandName, CommandArguments commandArgs) { _commandFactory = commandFactory; Config = config; Commands = commandName; Args = commandArgs; }
public void ParseInputConfigurationFileEmptyTest() { CommandArguments.Parse("Input.cs", "/c:"); }