예제 #1
0
        public override CommandInput GenerateRandomInput(string keyword)
        {
            var toReturn = new CommandInput();

            toReturn.Keyword = keyword;

            var i = 0;
            foreach (var part in Parts)
            {
                toReturn.Parameters.Add(new Parameter { Value = part.GenerateInput(), Index = i++ });
            }

            return toReturn;
        }
예제 #2
0
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.F1))
            {
                DisplayPanel.SetActive(!DisplayPanel.activeInHierarchy);

                ConsoleOpen = DisplayPanel.activeInHierarchy;

                if (ConsoleOpen)
                {
                    CommandInput.ActivateInputField();
                    CommandInput.Select();
                }
            }
        }
예제 #3
0
        public virtual bool TryRun(CommandInput ci, IOutput output, out IList<CommandError> errors)
        {
            errors = new List<CommandError>();

            foreach (var sig in this.Signatures)
            {
                if (sig.CanRun(ci))
                {
                    return sig.Run(ci, errors);
                }
            }

            errors.Add(new CommandError("Unknown parameters", "Current parameters can't be parsed"));
            return false;
        }
        public void Positive_ReadSingleIndexParameter()
        {
            var keyword        = "keyword";
            var parameterValue = "value";
            var line           = $"{keyword} {parameterValue}";

            var result = CommandInput.Parse(line);

            Assert.IsNotNull(result);
            Assert.AreEqual(keyword, result.Keyword);
            Assert.IsNotNull(result.Parameters);
            Assert.AreEqual(1, result.Parameters.Count);
            Assert.IsFalse(result.Parameters[0].IsNamed);
            Assert.AreEqual(parameterValue, result.Parameters[0].Value);
        }
예제 #5
0
        public virtual bool TryRun(CommandInput ci, IOutput output, out IList <CommandError> errors)
        {
            errors = new List <CommandError>();

            foreach (var sig in this.Signatures)
            {
                if (sig.CanRun(ci))
                {
                    return(sig.Run(ci, errors));
                }
            }

            errors.Add(new CommandError("Unknown parameters", "Current parameters can't be parsed"));
            return(false);
        }
예제 #6
0
        public CommandOutput OnExecute(CommandInput arguments)
        {
            var output = new CommandOutput {
                PostAction = CommandOutput.PostCommandAction.None
            };
            long suiteId = long.Parse(arguments["sid"]);
            long userId  = arguments.GetUserId();
            List <MappingModel> listOfMaps = CurrentHostContext.Default.Provider.ConfigurationStore.GetMapping(userId,
                                                                                                               suiteId);

            output.Data           = listOfMaps;
            output.DisplayMessage = "Success";

            return(output);
        }
예제 #7
0
파일: GetRegions.cs 프로젝트: ugurak/KonfDB
        public CommandOutput OnExecute(CommandInput arguments)
        {
            var output = new CommandOutput {
                PostAction = CommandOutput.PostCommandAction.None
            };
            long suiteId = -1;
            long userId  = arguments.GetUserId();

            long.TryParse(arguments["sid"], out suiteId);
            var model = CurrentHostContext.Default.Provider.ConfigurationStore.GetRegions(userId, suiteId);

            output.Data           = model;
            output.DisplayMessage = "Success";
            return(output);
        }
예제 #8
0
        public void GetTargetCommandSchema_Positive_Test(IReadOnlyList <CommandSchema> availableCommandSchemas,
                                                         CommandInput commandInput,
                                                         IReadOnlyList <string> expectedPositionalArguments,
                                                         string expectedCommandSchemaName)
        {
            // Arrange
            var resolver = new CommandSchemaResolver(new CommandArgumentSchemasValidator());

            // Act
            var commandCandidate = resolver.GetTargetCommandSchema(availableCommandSchemas, commandInput);

            // Assert
            commandCandidate.Should().NotBeNull();
            commandCandidate.PositionalArgumentsInput.Should().BeEquivalentTo(expectedPositionalArguments);
            commandCandidate.Schema.Name.Should().Be(expectedCommandSchemaName);
        }
예제 #9
0
        public override void Dispatch(CommandInput e)
        {
#if DEBUG_VERBOSE
            // DEBUG_VERBOSE because these serve almost no practical purpose when debugging
            ("Dispatch(" + _displayName + ") " + Convert.ToString(e)).Log();
#endif
            ServerTxPerformanceIncrement("CMD");
            try
            {
                Send(e);
            }
            catch
            {
                Control.Network.Server.RemoveClient(this);
            }
        }
예제 #10
0
            public bool Run()
            {
                if (!IsValid)
                {
                    return(false);
                }

                CommandInput commands = GetCommandInput();

                foreach (ArticulationJoint joint in _joints)
                {
                    joint.ApplyCommand(commands);
                }

                return(true);
            }
        public void Positive_ReadSingleSwitchParameters()
        {
            var keyword        = "keyword";
            var parameter1Name = "name";
            var line           = $"{keyword} -{parameter1Name}";

            var result = CommandInput.Parse(line);

            Assert.IsNotNull(result);
            Assert.AreEqual(keyword, result.Keyword);
            Assert.IsNotNull(result.Parameters);
            Assert.AreEqual(1, result.Parameters.Count);

            Assert.IsTrue(result.Parameters[0].IsNamed);
            Assert.AreEqual(null, result.Parameters[0].Value);
        }
예제 #12
0
        private void WriteCommandLineInput(CommandInput input)
        {
            // Command name
            if (!string.IsNullOrWhiteSpace(input.CommandName))
            {
                _console.WithForegroundColor(ConsoleColor.Cyan, () =>
                                             _console.Output.Write(input.CommandName));

                _console.Output.Write(' ');
            }

            // Parameters
            foreach (var parameter in input.Parameters)
            {
                _console.Output.Write('<');

                _console.WithForegroundColor(ConsoleColor.White, () =>
                                             _console.Output.Write(parameter));

                _console.Output.Write('>');
                _console.Output.Write(' ');
            }

            // Options
            foreach (var option in input.Options)
            {
                _console.Output.Write('[');

                _console.WithForegroundColor(ConsoleColor.White, () =>
                {
                    // Alias
                    _console.Output.Write(option.GetRawAlias());

                    // Values
                    if (option.Values.Any())
                    {
                        _console.Output.Write(' ');
                        _console.Output.Write(option.GetRawValues());
                    }
                });

                _console.Output.Write(']');
                _console.Output.Write(' ');
            }

            _console.Output.WriteLine();
        }
예제 #13
0
        private int?HandleHelpOption(CommandInput commandInput,
                                     IReadOnlyList <CommandSchema> availableCommandSchemas, CommandSchema targetCommandSchema)
        {
            // Help should be rendered if it was requested, or when executing a command which isn't defined
            var shouldRenderHelp = commandInput.IsHelpOptionSpecified() || targetCommandSchema == null;

            // If shouldn't render help, pass execution to the next handler
            if (!shouldRenderHelp)
            {
                return(null);
            }

            // Keep track whether there was an error in the input
            var isError = false;

            // If target command isn't defined, find its contextual replacement
            if (targetCommandSchema == null)
            {
                // If command was specified, inform the user that it's not defined
                if (commandInput.IsCommandSpecified())
                {
                    _console.WithForegroundColor(ConsoleColor.Red,
                                                 () => _console.Error.WriteLine($"Specified command [{commandInput.CommandName}] is not defined."));

                    isError = true;
                }

                // Replace target command with closest parent of specified command
                targetCommandSchema = availableCommandSchemas.FindParent(commandInput.CommandName);

                // If there's no parent, replace with stub default command
                if (targetCommandSchema == null)
                {
                    targetCommandSchema     = CommandSchema.StubDefaultCommand;
                    availableCommandSchemas = availableCommandSchemas.Concat(CommandSchema.StubDefaultCommand).ToArray();
                }
            }

            // Build help text source
            var helpTextSource = new HelpTextSource(_metadata, availableCommandSchemas, targetCommandSchema);

            // Render help text
            _helpTextRenderer.RenderHelpText(_console, helpTextSource);

            // Short-circuit with appropriate exit code
            return(isError ? -1 : 0);
        }
예제 #14
0
        /// <inheritdoc/>
        public async Task <int> ExecuteCommandAsync(IEnumerable <string> commandLineArguments)
        {
            _logger.LogInformation("Executing command '{CommandLineArguments}'.", commandLineArguments);

            using (IServiceScope serviceScope = _serviceScopeFactory.CreateScope())
            {
                IServiceProvider provider     = serviceScope.ServiceProvider;
                ICliContext      cliContext   = provider.GetRequiredService <ICliContext>();
                Guid             cliContextId = cliContext.Id;

                _logger.LogDebug("New scope created with CliContext {CliContextId}.", cliContextId);

                CommandInput input = CommandInputResolver.Parse(commandLineArguments, _rootSchemaAccessor.RootSchema.GetCommandNames());
                ((CliContext)cliContext).Input = input;

                try
                {
                    // Execute middleware pipeline
                    await RunPipelineAsync(provider, cliContext);
                }
                catch (Exception ex)
                {
                    _logger.LogDebug("Exception occured. Trying to find exception handler.");

                    IEnumerable <ICliExceptionHandler> exceptionHandlers = provider.GetServices <ICliExceptionHandler>();
                    foreach (ICliExceptionHandler handler in exceptionHandlers)
                    {
                        if (handler.HandleException(ex))
                        {
                            _logger.LogDebug(ex, "Exception handled by {ExceptionHandlerType}.", handler.GetType().FullName);

                            return(ExitCodes.FromException(ex));
                        }
                    }

                    _logger.LogCritical(ex, "Unhandled exception during command execution.");

                    throw;
                }
                finally
                {
                    _logger.LogDebug("Disposed scope with CliContext {CliContextId}.", cliContextId);
                }

                return(cliContext.ExitCode ?? ExitCodes.Error);
            }
        }
예제 #15
0
        private int?HandleVersionOption(CommandInput commandInput)
        {
            // Version should be rendered if it was requested on a default command
            var shouldRenderVersion = !commandInput.IsCommandSpecified() && commandInput.IsVersionOptionSpecified();

            // If shouldn't render version, pass execution to the next handler
            if (!shouldRenderVersion)
            {
                return(null);
            }

            // Render version text
            _console.Output.WriteLine(_metadata.VersionText);

            // Short-circuit with exit code 0
            return(0);
        }
예제 #16
0
        public void Test_RobotCommandFactory_ProvideCommandInput_RelatedCommandIsReturned()
        {
            var input        = new CommandInput("S", 2);
            var southCommand = RobotCommandProvider.GetCommand(input, new RobotPositioningContext());

            Assert.AreEqual(typeof(MoveSouthCommand), southCommand.GetType());

            var input2      = new CommandInput("E", 2);
            var eastCommand = RobotCommandProvider.GetCommand(input2, new RobotPositioningContext());

            Assert.AreEqual(typeof(MoveEastCommand), eastCommand.GetType());

            var input3       = new CommandInput("N", 4);
            var northCommand = RobotCommandProvider.GetCommand(input3, new RobotPositioningContext());

            Assert.AreEqual(typeof(MoveNorthCommand), northCommand.GetType());
        }
예제 #17
0
        private int?Execute(CliContext context)
        {
            CommandInput input = context.Input;

            // Get command schema from context
            CommandSchema commandSchema = context.CommandSchema;

            // Version option
            if (commandSchema.IsVersionOptionAvailable && input.IsVersionOptionSpecified)
            {
                context.Console.Output.WriteLine(context.Metadata.VersionText);

                return(ExitCodes.Success);
            }

            return(null);
        }
예제 #18
0
 private void SendInput(object sender, RoutedEventArgs e)
 {
     try
     {
         if (CommandInput.Text.ToString() == "q" && serverRunning)
         {
             _heartbeat.Stop();
             serverRunning            = false;
             StopServerBtn.IsEnabled  = false;
             StartServerBtn.IsEnabled = true;
         }
         ServerConsole.StandardInput.WriteLine(CommandInput.Text);
         ConsoleText.Text += CommandInput.Text + "\r\n";
         CommandInput.Clear();
     }
     catch { }
 }
예제 #19
0
    private void WriteCommandLineArguments(CommandInput commandInput)
    {
        Write("Command line:");
        WriteLine();

        WriteHorizontalMargin();

        // Command name
        if (!string.IsNullOrWhiteSpace(commandInput.CommandName))
        {
            Write(ConsoleColor.Cyan, commandInput.CommandName);
            Write(' ');
        }

        // Parameters
        foreach (var parameterInput in commandInput.Parameters)
        {
            Write('<');
            Write(ConsoleColor.White, parameterInput.Value);
            Write('>');
            Write(' ');
        }

        // Options
        foreach (var optionInput in commandInput.Options)
        {
            Write('[');

            // Identifier
            Write(ConsoleColor.White, optionInput.GetFormattedIdentifier());

            // Value(s)
            foreach (var value in optionInput.Values)
            {
                Write(' ');
                Write('"');
                Write(value);
                Write('"');
            }

            Write(']');
            Write(' ');
        }

        WriteLine();
    }
예제 #20
0
        public override CommandInput GenerateRandomInput(string keyword)
        {
            var toReturn = new CommandInput();

            toReturn.Keyword = keyword;

            var i = 0;

            foreach (var part in Parts)
            {
                toReturn.Parameters.Add(new Parameter {
                    Value = part.GenerateInput(), Index = i++
                });
            }

            return(toReturn);
        }
예제 #21
0
        public CommandOutput OnExecute(CommandInput arguments)
        {
            var output = new CommandOutput {
                PostAction = CommandOutput.PostCommandAction.None
            };
            var  suiteId = long.Parse(arguments["sid"]);
            long userId  = arguments.GetUserId();
            var  success = CurrentHostContext.Default.Provider.ConfigurationStore.DeleteSuite(new SuiteModel
            {
                UserId  = userId,
                SuiteId = suiteId
            });

            output.DisplayMessage = success ? "Suite deleted successfully!" : "Could not delete suite";

            return(output);
        }
예제 #22
0
 private void CommandInput_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key != Key.Enter)
     {
         return;
     }
     if (CommandInput.Text.ToString() == "q" && serverRunning)
     {
         _heartbeat.Stop();
         serverRunning            = false;
         StopServerBtn.IsEnabled  = false;
         StartServerBtn.IsEnabled = true;
         ServerConsole.StandardInput.WriteLine(CommandInput.Text);
         ConsoleText.Text += CommandInput.Text + "\r\n";
     }
     CommandInput.Clear();
 }
예제 #23
0
        public CommandOutput OnExecute(CommandInput arguments)
        {
            var output = new CommandOutput {
                PostAction = CommandOutput.PostCommandAction.None
            };
            bool       completed = false;
            SuiteModel model     = default(SuiteModel);
            long       userId    = arguments.GetUserId();

            if (arguments["name"] != null)
            {
                model     = CurrentHostContext.Default.Provider.ConfigurationStore.GetSuite(userId, arguments["name"]);
                completed = true;
            }
            else if (arguments["id"] != null)
            {
                long suiteId = -1;
                long.TryParse(arguments["id"], out suiteId);

                if (suiteId != -1)
                {
                    model     = CurrentHostContext.Default.Provider.ConfigurationStore.GetSuite(userId, suiteId);
                    completed = true;
                }
            }

            if (!completed)
            {
                output.DisplayMessage = "Invalid data in command received";
                output.PostAction     = CommandOutput.PostCommandAction.ShowCommandHelp;
                output.MessageType    = CommandOutput.DisplayMessageType.Error;
            }
            else if (model != null)
            {
                output.Data           = model;
                output.DisplayMessage = "Success";
            }
            else
            {
                output.DisplayMessage = DoesNotExist;
                output.MessageType    = CommandOutput.DisplayMessageType.Error;
            }

            return(output);
        }
예제 #24
0
        private void OnListViewKeyUp(object sender, KeyEventArgs e)
        {
            var listview = e.Source as ListView;

            if (e.Key == Key.Enter)
            {
                ViewModel.Send();
            }

            if (e.Key == Key.Escape)
            {
                CommandInput.Focus();
            }

            if (e.KeyboardDevice.Modifiers.HasFlag(ModifierKeys.Control))
            {
                if (e.Key == Key.C)
                {
                    var text = String.Join("\r\n", listview.SelectedItems.Cast <Object>());
                    Clipboard.SetText(text);
                }

                if (e.Key == Key.V)
                {
                    ViewModel.Send(Clipboard.GetText());
                }


                if (e.Key == Key.M)
                {
                    MeasureAverage(listview);
                    return;
                }

                if (e.Key == Key.T)
                {
                    RebaseSelected(listview);
                }
                //if (e.Key == Key.V)
                //{
                //    Clipboard.GetText().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                //    ViewModel.Send();
                //}
            }
        }
예제 #25
0
        public List <StreamIdentifier> Add(CommandInput resource)
        {
            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }

            resource.Owner = Owner;

            if (Owner.Objects.ContainsInput(resource))
            {
                throw new ArgumentException("Command already contains the specified resource.", "resource");
            }

            Owner.Objects.Inputs.Add(resource);

            return(resource.GetStreamIdentifiers());
        }
예제 #26
0
        private void ExecuteCommand()
        {
            if (CommandInput.Text.Length == 0)
            {
                return;                                // prevent empty commands
            }
            if (CommandInput.Text.ToUpper().Equals("EXIT"))
            {
                Application.Current.Shutdown();
            }
            else
            {
                listener.SendCommand(CommandInput.Text);
            }

            CommandLog.AppendText("> " + CommandInput.Text + "\r\n");
            CommandInput.Clear();
        }
예제 #27
0
        public List<StreamIdentifier> Insert(int index, CommandInput resource)
        {
            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }

            resource.Owner = Owner;

            if (Owner.Objects.ContainsInput(resource))
            {
                throw new ArgumentException("Command already contains the specified resource.", "resource");
            }

            Owner.Objects.Inputs.Insert(index, resource);

            return resource.GetStreamIdentifiers();
        }
예제 #28
0
        private int?Execute(CliContext context)
        {
            // Get input and command schema from context
            CommandInput  input         = context.Input;
            CommandSchema commandSchema = context.CommandSchema;

            // Help option
            if ((commandSchema.IsHelpOptionAvailable && input.IsHelpOptionSpecified) ||
                (commandSchema == StubDefaultCommand.Schema && !input.Parameters.Any() && !input.Options.Any()))
            {
                IHelpWriter helpTextWriter = new DefaultHelpWriter(context);
                helpTextWriter.Write(commandSchema, context.CommandDefaultValues);

                return(ExitCodes.Success);
            }

            return(null);
        }
예제 #29
0
        public CommandOutput OnExecute(CommandInput arguments)
        {
            var output = new CommandOutput {
                PostAction = CommandOutput.PostCommandAction.None
            };
            long     suiteId        = long.Parse(arguments["sid"]);
            string   username       = arguments["user"];
            long     loggedInUserId = arguments.GetUserId();
            RoleType role           = arguments.HasArgument("role") ? arguments["role"].ToEnum <RoleType>() : RoleType.ReadOnly;
            bool     success        = CurrentHostContext.Default.Provider.ConfigurationStore.GrantRoleAccessToSuite(suiteId,
                                                                                                                    loggedInUserId,
                                                                                                                    username, role);

            output.Data           = success;
            output.DisplayMessage = success
                ? "Grants added successfully"
                : "Some problem occured while granting rights to user";
            return(output);
        }
예제 #30
0
        public CommandOutput OnExecute(CommandInput arguments)
        {
            var output = new CommandOutput {
                PostAction = CommandOutput.PostCommandAction.None
            };
            long   suiteId        = long.Parse(arguments["sid"]);
            string username       = arguments["user"];
            long   loggedInUserId = arguments.GetUserId();

            bool success = CurrentHostContext.Default.Provider.ConfigurationStore.RevokeRoleAccessToSuite(suiteId,
                                                                                                          loggedInUserId, username);

            output.Data           = success;
            output.DisplayMessage = success
                ? "Grants revoked successfully"
                : "Some problem occured while revoking rights from user";

            return(output);
        }
예제 #31
0
            public void ApplyCommand(CommandInput commands)
            {
                float response = GetResponse(commands);

                if (joint_type == ArticulationType.piston)
                {
                    IMyPistonBase piston = (IMyPistonBase)joint; //should throw exception if this does not work
                    piston.Velocity = response;
                    return;
                }
                if (joint_type == ArticulationType.rotor)
                {
                    IMyMotorStator rotor = (IMyMotorStator)joint; //should throw exception if this does not work
                    rotor.TargetVelocityRPM = response;
                    return;
                }

                throw new Exception($"Error in CommandGroup.ApplyCommandResponse: Unrecognized joint type: {joint_type.ToString()}");
            }
예제 #32
0
파일: NewParam.cs 프로젝트: ugurak/KonfDB
        public CommandOutput OnExecute(CommandInput arguments)
        {
            var output = new CommandOutput {
                PostAction = CommandOutput.PostCommandAction.None
            };
            var  name        = arguments["name"];
            long suiteId     = long.Parse(arguments["sid"]);
            var  value       = arguments["val"];
            var  isEncrypted = arguments.HasArgument("protect");
            long userId      = arguments.GetUserId();

            if (isEncrypted)
            {
                var suite = CurrentHostContext.Default.Provider.ConfigurationStore.GetSuite(userId, suiteId);
                if (suite != null)
                {
                    value = EncryptionEngine.Default.Encrypt(value, suite.PublicKey, null);
                }
                else
                {
                    output.DisplayMessage = "Could not retrieve suite :" + suiteId;
                    output.MessageType    = CommandOutput.DisplayMessageType.Error;
                    output.PostAction     = CommandOutput.PostCommandAction.ShowCommandHelp;

                    return(output);
                }
            }

            var parameter = CurrentHostContext.Default.Provider.ConfigurationStore.AddParameter(new ParameterModel
            {
                ParameterName  = name,
                ParameterValue = string.IsNullOrEmpty(value) ? string.Empty : value,
                IsActive       = true,
                IsEncrypted    = isEncrypted,
                SuiteId        = suiteId,
                UserId         = userId
            });

            output.Data           = parameter;
            output.DisplayMessage = "Success";

            return(output);
        }
예제 #33
0
        //read function
        public void GetInput()
        {
            ListMessages.Add(CommandInput);

            List <string> listOfParams = new List <string>();

            listOfParams = CommandInput.Split(' ').ToList();

            if (listOfParams[0] == "depend")
            {
                CommandInput = "";
                Messages     = "Adding Dependencies";
                AddDependency(listOfParams);
            }
            else if (listOfParams[0] == "install")
            {
                CommandInput = "";
                Messages     = "";
                InstallComponent(listOfParams[1]);
            }
            else if (listOfParams[0] == "remove")
            {
                CommandInput = "";
                Messages     = "";
                RemoveComponent(listOfParams[1]);
            }
            else if (listOfParams[0] == "list")
            {
                CommandInput = "";
                Messages     = "Displaying list of installed Components";
                ListInstalledComponents();
            }
            else if (listOfParams[0] == "end")
            {
                Messages = "Ending Component Installation";
            }
            else
            {
                Messages = "No command detected, no action taken";
            }
            OutputList = ListMessages;
        }
예제 #34
0
        public override bool CanRun(CommandInput ci)
        {
            if (ci.Keyword != Keyword)
            {
                return false;
            }

            if (ci.IndexParameters.Count != this.ParameterCount)
            {
                return false;
            }

            for (var i = 0; i < ci.IndexParameters.Count; i++)
            {
                if (!this.Parts[i].CanParse(ci.IndexParameters[i]))
                {
                    return false;
                }
            }

            return true;
        }
예제 #35
0
 public override bool Run(CommandInput ci, IList<CommandError> errors)
 {
     return this._callback?.Invoke(ci, errors) ?? false;
 }
예제 #36
0
        private void WriteResourcePreSettings(CommandInput resource)
        {
            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }

            resource.Settings.SettingsList.ForEach(setting =>
            {
                if (!setting.IsPreSetting()) return;

                BuilderBase.Append(" ");
                BuilderBase.Append(SettingSerializer.Serialize(setting));
            });
        }
예제 #37
0
        private void WriteResource(CommandInput resource)
        {
            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }

            WriteResourcePreSettings(resource);

            var inputResource = new Input(resource.Resource);
            BuilderBase.Append(" ");
            BuilderBase.Append(SettingSerializer.Serialize(inputResource));

            WriteResourcePostSettings(resource);
        }
예제 #38
0
 public bool ContainsInput(CommandInput commandInput)
 {
     return Inputs.Any(input => input.Id == commandInput.Id);
 }
        public static MetadataInfoStreamCalculator Create(CommandInput commandResource)
        {
            var infoStreamItem = MetadataInfoTreeSource.Create(commandResource);

            return new MetadataInfoStreamCalculator(infoStreamItem);
        }
예제 #40
0
        private void WriteResourcePreSettings(CommandInput resource, Dictionary<Type, SettingsApplicationData> settingsData)
        {
            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }

            resource.Settings.SettingsList.ForEach(setting =>
            {
                var settingInfoData = settingsData[setting.GetType()];
                if (settingInfoData == null) return;
                if (!settingInfoData.PreDeclaration) return;
                if (settingInfoData.ResourceType != SettingsCollectionResourceType.Input) return;

                _builderBase.Append(" ");
                _builderBase.Append(setting.GetAndValidateString());
            });
        }
예제 #41
0
 public abstract bool Run(CommandInput ci, IList<CommandError> errors);
예제 #42
0
        private void WriteResource(CommandInput resource)
        {
            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }

            var settingsData = Validate.GetSettingCollectionData(resource.Settings);

            WriteResourcePreSettings(resource, settingsData);

            var inputResource = new Input(resource.Resource);
            _builderBase.Append(" ");
            _builderBase.Append(inputResource);

            WriteResourcePostSettings(resource, settingsData);
        }
예제 #43
0
 public abstract bool CanRun(CommandInput ci);
        public static MetadataInfoTreeSource Create(CommandInput commandResource)
        {
            var treeSourceFromInput = new MetadataInfoTreeSource(commandResource.Resource, commandResource.Settings);

            return treeSourceFromInput;
        }
예제 #45
0
        public void ProcessInput(CommandInput input, bool findSimilar)
        {
            if (this.Commands.Any(x => string.IsNullOrWhiteSpace(x.Keyword)))
            {
                throw new ApplicationException("Some commands have no keyword set.");
            }

            var commands = this.Commands.Where(x => x.Keyword == input.Keyword).ToList();

            if (commands.Any())
            {
                if (commands.Count == 1)
                {
                    var exec = commands.Single();
                    this.FoundCommand(this.Output, input, exec);
                }
                else
                {
                    throw new ApplicationException($"More commands with same name: {input.Keyword}");
                }
            }
            else
            {
                this.UnknownCommand(this.Output, input);
            }
        }