示例#1
0
        static void Main(string[] args)
        {
            CommandInputParser commandInputParser = new CommandInputParser();
            Calculator         calculator         = new Calculator();
            InputService       inputService       = new InputService();

            while (true)
            {
                string command = inputService.ReadCommand();

                try
                {
                    CommandTypes commandType = commandInputParser.ParseCommand(command);

                    int[] arguments = inputService.ReadArguments();

                    int result = calculator.Calculate(commandType, arguments[0], arguments[1]);

                    Console.WriteLine("Result: " + result);
                }
                catch (Exception)
                {
                    Console.WriteLine("Mistake!");
                }
            }
        }
示例#2
0
        internal static ICommand GetCommand(string commandName)
        {
            if (commandName == null)
            {
                WriteHelp();
                return(null);
            }
            if (HelpStrings.Contains(commandName.ToLowerInvariant()))
            {
                WriteHelp();
                return(null);
            }

            var commandType =
                CommandTypes.FirstOrDefault(t =>
                                            t.Name.Equals(commandName, StringComparison.OrdinalIgnoreCase) ||
                                            t.Name.Equals(commandName + "command", StringComparison.OrdinalIgnoreCase));

            if (commandType != null)
            {
                return((ICommand)Activator.CreateInstance(commandType));
            }

            WriteError($"Unknown command: {commandName}\r\n{GetAvailableCommandsMessage()}");
            return(null);
        }
示例#3
0
    public ICommand CreateCommand(CommandTypes commandType)
    {
        ICommand command = null;

        switch (commandType)
        {
        case CommandTypes.SpawnCube:
            command = new SpawnCubeCommand();
            break;

        case CommandTypes.SpawnSphere:
            command = new SpawnSphereCommand();
            break;

        case CommandTypes.SpawnPlayer:
            command = new SpawnPlayerCommand();
            break;

        case CommandTypes.Delete:
            command = new DeleteCommand();
            break;

        case CommandTypes.SpawnWall:
            command = new SpawnWallCommand();
            break;

        case CommandTypes.SpawnEnemySpawner:
            command = new SpawnEnemySpawnerCommand();
            break;
        }

        return(command);
    }
示例#4
0
        public void Do(CommandTypes current)
        {
            switch (current)
            {
            case CommandTypes.Unknown:
                Console.WriteLine("Unknown command!");
                break;

            case CommandTypes.Start:
                Console.WriteLine("Starting...");
                break;

            case CommandTypes.Load:
                Console.WriteLine("Loading...");
                break;

            case CommandTypes.Run:
                Console.WriteLine("RUN");
                break;

            case CommandTypes.Unload:
                Console.WriteLine("Unloading...");
                break;

            case CommandTypes.Stop:
                Console.WriteLine("Stopped.");
                break;
            }
        }
示例#5
0
        public static void IncrementData(CommandTypes cmdType)
        {
            if (!isWinSQMEnabled)
            {
                return;
            }
            PSSqmDataPoint cmdlet = PSSqmDataPoint.Cmdlet;
            CommandTypes   types  = cmdType;

            if (types <= CommandTypes.ExternalScript)
            {
                switch (types)
                {
                case CommandTypes.Alias:
                    cmdlet = PSSqmDataPoint.Alias;
                    goto Label_008B;

                case CommandTypes.Function:
                    cmdlet = PSSqmDataPoint.Function;
                    goto Label_008B;

                case (CommandTypes.Function | CommandTypes.Alias):
                    return;

                case CommandTypes.Filter:
                    cmdlet = PSSqmDataPoint.Filter;
                    goto Label_008B;

                case CommandTypes.Cmdlet:
                    cmdlet = PSSqmDataPoint.Cmdlet;
                    goto Label_008B;

                case CommandTypes.ExternalScript:
                    cmdlet = PSSqmDataPoint.ExternalScript;
                    goto Label_008B;
                }
                return;
            }
            if (types != CommandTypes.Application)
            {
                if (types != CommandTypes.Script)
                {
                    if (types != CommandTypes.Workflow)
                    {
                        return;
                    }
                    cmdlet = PSSqmDataPoint.Function;
                }
                else
                {
                    cmdlet = PSSqmDataPoint.Script;
                }
            }
            else
            {
                cmdlet = PSSqmDataPoint.Application;
            }
Label_008B:
            IncrementDataPoint((int)cmdlet);
        }
示例#6
0
 public RenderOperation(int startIndex, int primitiveCount)
 {
     CommandType    = CommandTypes.Render;
     StartIndex     = startIndex;
     PrimitiveCount = primitiveCount;
     Size           = sizeof(RenderOperation);
 }
示例#7
0
 public CameraOperation(RenderCameraType cameraType, Matrix matrix)
 {
     CommandType      = CommandTypes.Camera;
     RenderCameraType = cameraType;
     Matrix           = matrix;
     Size             = sizeof(CameraOperation);
 }
示例#8
0
 public void SetRequestData(CommandTypes commandType, byte[] data)
 {
     this.IsBroadcastCommand = false;
     this.RequestData        = data;
     this.ResponseData       = null;
     this.CommandType        = commandType;
 }
示例#9
0
        /// <summary>
        /// Devuelve una instancia de LenzResponse.
        /// </summary>
        /// <param name="type">Tipo de respuesta recibida.</param>
        /// <param name="data">Información /bytes) recibida.</param>
        public bool SetResponseData(byte[] data)
        {
            // Controla el caso de no tener datos
            if (data == null)
            {
                this.CommandType = CommandTypes.Unknown;
                return(false);
            }

            // Comprueba que los dos bytes corresponden a los frames LI-USB
            if (data[0] == 0xFF && (data[1] == 0xFD || data[1] == 0xFE))
            {
                // Copia los datos quitando los dos bytes (frame)
                this.ResponseData = this.RemoveFrame(data);

                // Check if response if of the same wanted type
                if (this.CommandType != this.GetResponseType(this.ResponseData))
                {
                    return(false);
                }

                // Check the integrity of the data received
                this.IsResponseReceived = this.CheckData(this.ResponseData);

                return(this.IsResponseReceived);
            }
            else
            {
                this.CommandType = CommandTypes.Unknown;
                return(false);
            }
        }
示例#10
0
        private IDictionary <string, ModuleMetadata> BuildModuleIndex(Collection <PSObject> commandList)
        {
            Dictionary <string, ModuleMetadata> moduleIndex = new Dictionary <string, ModuleMetadata>();

            foreach (PSObject commandObj in commandList)
            {
                string       moduleName  = (string)commandObj.Properties["Source"].Value;
                string       commandName = (string)commandObj.Properties["Name"].Value;
                CommandTypes commandType = (CommandTypes)commandObj.Properties["CommandType"].Value;

                var commandParts = commandName.Split('-');

                if ((commandType == CommandTypes.Function ||
                     commandType == CommandTypes.Cmdlet) &&
                    commandParts.Length == 2)
                {
                    string noun = commandParts[1];
                    string verb = commandParts[0];

                    ModuleMetadata moduleMetadata = null;

                    if (!moduleIndex.TryGetValue(moduleName, out moduleMetadata))
                    {
                        moduleMetadata = new ModuleMetadata {
                            Name = moduleName
                        };
                        moduleIndex.Add(moduleName, moduleMetadata);
                    }

                    moduleMetadata.AddCommand(verb, noun);
                }
            }

            return(moduleIndex);
        }
示例#11
0
        // Outputs phrase if command was executed successfully.
        public static void CommandSucceed(CommandTypes command)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            switch (command)
            {
            case CommandTypes.create:
                Console.WriteLine("\nNew note was created successfully!\n");
                break;

            case CommandTypes.delete:
                Console.WriteLine("\nNote was deleted successfully!\n");
                break;

            case CommandTypes.edit:
                Console.WriteLine("\nNote was edited successfully!\n");
                break;

            default:
                CommandInput(false);
                return;
            }
            Console.ResetColor();
            System.Threading.Thread.Sleep(1000);
            CommandInput();
        }
示例#12
0
 public CommandMetadata(CommandInfo commandInfo, bool shouldGenerateCommonParameters)
 {
     if (commandInfo == null)
     {
         throw CommandMetadata.tracer.NewArgumentNullException(nameof(commandInfo));
     }
     while (commandInfo is AliasInfo)
     {
         commandInfo = ((AliasInfo)commandInfo).ResolvedCommand;
         if (commandInfo == null)
         {
             throw CommandMetadata.tracer.NewNotSupportedException();
         }
     }
     if (commandInfo is CmdletInfo cmdletInfo)
     {
         this.Init(cmdletInfo.ImplementingType, shouldGenerateCommonParameters);
     }
     else if (commandInfo is ExternalScriptInfo externalScriptInfo)
     {
         this.Init(externalScriptInfo.ScriptBlock, externalScriptInfo.Path, shouldGenerateCommonParameters);
         this.wrappedCommandType = CommandTypes.ExternalScript;
     }
     else
     {
         if (!(commandInfo is FunctionInfo functionInfo))
         {
             throw CommandMetadata.tracer.NewNotSupportedException();
         }
         this.Init(functionInfo.ScriptBlock, functionInfo.Name, shouldGenerateCommonParameters);
         this.wrappedCommandType = commandInfo.CommandType;
     }
 }
示例#13
0
        static void Main(string[] args)
        {
            CommandInputParser commandInputParser = new CommandInputParser();
            Calculator         calculator         = new Calculator();

            while (true)
            {
                Console.Write("Operation: ");
                string command = Console.ReadLine();

                try
                {
                    CommandTypes commandType = commandInputParser.ParseCommand(command);

                    Console.Write("Value 1: ");
                    int x = int.Parse(Console.ReadLine());

                    Console.Write("Value 2: ");
                    int y = int.Parse(Console.ReadLine());

                    int result = calculator.Calculate(commandType, x, y);

                    Console.WriteLine("Result: " + result);
                }
                catch (Exception)
                {
                    Console.WriteLine("Mistake!");
                }
            }
        }
示例#14
0
        private int CommandProcess(CommandTypes commandType, AppOptions options)
        {
            int result = 0;

            ProcessModel model = new ProcessModel
            {
                ProcessId   = options.ProcessId,
                PathExe     = options.PathExe,
                ProcessName = options.ProcessName,
                Arguments   = options.Arguments
            };

            CmdProcessRequest request = new CmdProcessRequest(1, commandType, model);

            if (!client.SendCommand(request))
            {
                result = 1;
            }
            else
            {
                waitAnswer.WaitOne();
            }

            return(result);
        }
示例#15
0
        public void SendTimeCommand(string mac, string time, string buffer, CommandTypes type)
        {
            TimeCommand tc = new TimeCommand(type, time, buffer);

            //NetworkCommand nc = new NetworkCommand(type, time, buffer);
            nu.DirectMessage(tc.ToJson(), mac);
        }
        /// <summary>
        /// Calculates a possibly command, in dependence of digital properties,
        /// return true if should command to Simulator.
        /// </summary>
        /// <param name="digital"></param>
        /// <param name="command"></param>
        /// <returns></returns>
        public static bool InitialCommandingForDigital(Digital digital, out CommandTypes command)
        {
            // ovde nema neke velike logike za sada, ali je ideja da kasnije nekad bude ...prosirivo? xD

            command = CommandTypes.OPEN;

            // if previously states was OPENED, OPEN it again
            if (digital.State == States.OPEN)
            {
                command = CommandTypes.OPEN;
                return(true);
            }

            if (digital.State == States.CLOSED && digital.Command == CommandTypes.OPEN)
            {
                command = CommandTypes.OPEN;
                return(true);
            }

            /*
             * if (digital.State==States.OPENED && digital.Command == CommandTypes.CLOSE)
             * {
             *  // to do: ...
             * }*/

            return(false);
        }
        public static bool ValidateDigitalCommand(Digital digital, CommandTypes command)
        {
            bool retVal = true;

            if (digital.ValidCommands.Contains(command))
            {
                switch (command)
                {
                case CommandTypes.CLOSE:

                    //  command is CLOSE, last command was CLOSE, and state is CLOSED -> invalid...
                    if (digital.State == States.CLOSED && digital.Command == CommandTypes.CLOSE)
                    {
                        retVal = false;
                    }

                    // command is CLOSE, last command was CLOSE, but state is OPENED (incident) -> valid

                    break;

                case CommandTypes.OPEN:
                    if (digital.State == States.OPEN && digital.Command == CommandTypes.OPEN)
                    {
                        retVal = false;
                    }

                    break;
                }
            }
            return(retVal);
        }
示例#18
0
 public static string Serialize(CommandTypes command)
 {
     return(Serialize(new JSONCommand()
     {
         Command = command
     }));
 }
示例#19
0
        /// <summary>
        /// Returns a command info for a given command name and type, using the specified arguments
        /// to resolve dynamic parameters.
        /// </summary>
        /// <param name="commandName">The command name to search for.</param>
        /// <param name="type">The command type to search for.</param>
        /// <param name="arguments">The command arguments used to resolve dynamic parameters.</param>
        /// <returns>A CommandInfo result that represents the resolved command.</returns>
        public CommandInfo GetCommand(string commandName, CommandTypes type, object[] arguments)
        {
            CommandInfo result = null;

            try
            {
                CommandOrigin commandOrigin = CommandOrigin.Runspace;
                if (_cmdlet != null)
                {
                    commandOrigin = _cmdlet.CommandOrigin;
                }
                else if (_context != null)
                {
                    commandOrigin = _context.EngineSessionState.CurrentScope.ScopeOrigin;
                }

                result = CommandDiscovery.LookupCommandInfo(commandName, type, SearchResolutionOptions.None, commandOrigin, _context);

                if ((result != null) && (arguments != null) && (arguments.Length > 0))
                {
                    // We've been asked to retrieve dynamic parameters
                    if (result.ImplementsDynamicParameters)
                    {
                        result = result.CreateGetCommandCopy(arguments);
                    }
                }
            }
            catch (CommandNotFoundException) { }

            return(result);
        }
示例#20
0
 public ApiOperation(bool isExclusive, CommandTypes serialApiCommand, bool isSequenceNumberRequired)
     : base(isExclusive)
 {
     SerialApiCommands        = new CommandTypes[] { serialApiCommand };
     IsSequenceNumberRequired = isSequenceNumberRequired;
     SubstituteSettings       = new SubstituteSettings();
 }
 public JointCommandObject(string n)
 {
     name        = n;
     commandType = CommandTypes.Position;
     targetValue = 0;
     period      = 3.0f;
 }
示例#22
0
        void handleButtonPressed(object sender, CommandTypes buttonType)
        {
            switch (buttonType)
            {
            case CommandTypes.EJECT:
                if (!isToggledSuspended)
                {
                    gameInputBridge.eject();
                }
                break;

            case CommandTypes.QUIT:
                isToggledSuspended = !isToggledSuspended;
                break;

            case CommandTypes.SPLIT:
                if (!isToggledSuspended)
                {
                    gameInputBridge.split();
                }
                break;

            case CommandTypes.SUSPEND:
                if (!isToggledSuspended)
                {
                    isSuspended = true;
                }
                break;
            }
        }
示例#23
0
        protected void HandleCommand(CommandTypes command)
        {
            switch (command)
            {
            case CommandTypes.Create:
                break;

            case CommandTypes.Delete:
                Delete();
                break;

            case CommandTypes.Remove:
                break;

            case CommandTypes.Update:
                Refresh();
                break;

            case CommandTypes.Commit:
                CommitUpdates();
                break;

            default:
                break;
            }
        }
示例#24
0
        private void HandleData()
        {
            lock (dataQueue)
            {
                while (dataQueue.Count > 8)
                {
                    int          length = CommandParser.ParseBodyLength(dataQueue.ToArray(), 0, dataQueue.Count);
                    CommandTypes type   = CommandParser.ParseCommandType(dataQueue.Skip(4).Take(4).ToArray());

                    if (length <= dataQueue.Count)
                    {
                        // Skip header bytes
                        for (int i = 0; i < 8; ++i)
                        {
                            dataQueue.Dequeue();
                        }

                        byte[] data = new byte[length];
                        for (int i = 0; i < length; ++i)
                        {
                            data[i] = dataQueue.Dequeue();
                        }

                        DispatchData(type, data);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
示例#25
0
 void handleButtonReleased(object sender, CommandTypes buttonType)
 {
     if (buttonType == CommandTypes.SUSPEND && !isToggledSuspended)
     {
         isSuspended = false;
     }
 }
示例#26
0
 public void Clear()
 {
     _headerPartFromPreviousChunk = new byte[0];
     _currentCommand = null;
     _currentCommandExpectedLength = 0;
     _currentCommandName           = CommandTypes.Unknown;
 }
示例#27
0
 public virtual void sendButtonReleased(CommandTypes button)
 {
     if (ButtonReleased != null)
     {
         ButtonReleased(this, button);
     }
 }
示例#28
0
        private CommandMetadata RehydrateCommandMetadata(PSObject deserializedCommandInfo, out string resolvedCommandName)
        {
            if (deserializedCommandInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException("deserializedCommandInfo");
            }
            string       aliasName   = this.GetPropertyValue <string>("Get-Command", deserializedCommandInfo, "Name");
            CommandTypes commandType = this.GetPropertyValue <CommandTypes>("Get-Command", deserializedCommandInfo, "CommandType");

            if (commandType == CommandTypes.Alias)
            {
                resolvedCommandName = this.GetPropertyValue <string>("Get-Command", deserializedCommandInfo, "ResolvedCommandName", true);
                if (string.IsNullOrEmpty(resolvedCommandName))
                {
                    base.WriteError(this.GetErrorCouldntResolvedAlias(aliasName));
                }
            }
            else
            {
                resolvedCommandName = null;
            }
            Dictionary <string, ParameterMetadata> parameters = this.RehydrateDictionary <string, ParameterMetadata>("Get-Command", deserializedCommandInfo, "Parameters", new Converter <PSObject, ParameterMetadata>(this.RehydrateParameterMetadata));

            parameters.Remove("AsJob");
            ParameterMetadata metadata = new ParameterMetadata("AsJob", typeof(SwitchParameter));

            parameters.Add(metadata.Name, metadata);
            return(new CommandMetadata(aliasName, commandType, this.IsProxyForCmdlet(parameters), "__AllParameterSets", false, ConfirmImpact.None, false, false, true, parameters));
        }
示例#29
0
        private static bool AddPsd1EntryToResult(ConcurrentDictionary <string, CommandTypes> result, string command, CommandTypes commandTypeToAdd, ref bool sawWildcard)
        {
            if (WildcardPattern.ContainsWildcardCharacters(command))
            {
                sawWildcard = true;
                return(false);
            }

            // An empty string is one way of saying "no exported commands".
            if (command.Length != 0)
            {
                CommandTypes commandTypes;
                if (result.TryGetValue(command, out commandTypes))
                {
                    commandTypes |= commandTypeToAdd;
                }
                else
                {
                    commandTypes = commandTypeToAdd;
                }

                result[command] = commandTypes;
            }

            return(true);
        }
示例#30
0
        public Command MappCommand(TypeOfSCADACommand typeOfCommand, string mrid, CommandTypes command, float value)
        {
            switch (typeOfCommand)
            {
            case TypeOfSCADACommand.ReadAll:
                return(new ReadAll());

            case TypeOfSCADACommand.WriteAnalog:
                return(new WriteSingleAnalog()
                {
                    Id = mrid, Value = value
                });

            case TypeOfSCADACommand.WriteDigital:
                return(new WriteSingleDigital()
                {
                    Id = mrid, CommandType = command
                });
            }

            return(null);
            ////naapirati klijentsku komandu na scada komandu
            //ReadAll readAllCommand = new ReadAll();
            //return readAllCommand;
        }
示例#31
0
        public Command(FileManager manager, IPathInfo[] operands, int expectedOperandCount, CommandTypes commandType)
        {
            if (operands.Length != expectedOperandCount)
                throw new CommandFormatException(commandType.ToString());

            _manager = manager;
            _operands = operands;
            _commandType = commandType;
        }
示例#32
0
 internal CommandInfo(string name, CommandTypes type)
 {
     this._name = string.Empty;
     this._type = CommandTypes.Application;
     this._prefix = "";
     if (name == null)
     {
         throw new ArgumentNullException("name");
     }
     this._name = name;
     this._type = type;
 }
示例#33
0
        //finds the command to use
        private void _DetectCommandType()
        {
            this._TryLocateSwitch("-list", CommandTypes.List);
            this._TryLocateSwitch("-help", CommandTypes.Help);
            this._TryLocateSwitch("-remove", CommandTypes.Remove);
            this._TryLocateSwitch("-add", CommandTypes.Add);
            this._TryLocateSwitch("-help", CommandTypes.Add);

            //check to see if this might just be a command to execute
            if (this._CommandType != CommandTypes.Undefined) return;
            if (!string.IsNullOrEmpty(this.Command)) this._CommandType = CommandTypes.Run;
            if (string.IsNullOrEmpty(this.Command)) this._CommandType = CommandTypes.Help;
        }
示例#34
0
        private void ParseCommandType(string[] substrings)
        {
            string commandName = substrings[0];

            try
            {
                _commandType = (CommandTypes) Enum.Parse(typeof (CommandTypes), commandName, true);
            }
            catch (Exception)
            {
                throw new UnknownCommandException(commandName);
            }
        }
示例#35
0
 internal CommandInfo(CommandInfo other)
 {
     this._name = string.Empty;
     this._type = CommandTypes.Application;
     this._prefix = "";
     this._module = other._module;
     this._visibility = other._visibility;
     this._arguments = other._arguments;
     this.Context = other.Context;
     this._name = other._name;
     this._type = other._type;
     this._copiedCommand = other;
     this.DefiningLanguageMode = other.DefiningLanguageMode;
 }
        private CommandTypes _type; // Message type

        #endregion Fields

        #region Constructors

        public ArduinoCommand(CommandTypes type, string target, string command, string origin)
        {
            // Set properties
            Type = type;
            if (target != "" && command != "" && origin != "")
            {
                Target = target.Trim();
                Content = command.Trim();
                Origin = origin.Trim();
            }

            // Verify that the command fulfills the specification
            VerifyFaultiness();
        }
示例#37
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="CommandModel" /> class.
        /// </summary>
        /// <param name="familiarName">
        ///     The familiar name.
        /// </param>
        /// <param name="serverName">
        ///     The server name.
        /// </param>
        /// <param name="paramaterNames">
        ///     The paramater names.
        /// </param>
        /// <param name="typeOfCommand">
        ///     The type of command.
        /// </param>
        /// <param name="permissionLevel">
        ///     The permission level.
        /// </param>
        public CommandModel(
            string familiarName,
            string serverName,
            IList<string> paramaterNames = null,
            CommandTypes typeOfCommand = CommandTypes.SingleSentence,
            PermissionLevel permissionLevel = PermissionLevel.User)
        {
            this.familiarName = familiarName;
            ServerName = serverName;
            CommandType = typeOfCommand;
            PermissionsLevel = permissionLevel;

            ArgumentNames = paramaterNames;
        }
        public CommandInfo GetCommand(string command, CommandTypes commandTypes)
        {
            // Annoying special-case hack needed until NuGet can call init.ps1 in the same scope as the console.
            // This gets called implicitly while resolving dynamic params, and that call happens in a scope where
            // there is more than one copy of the T4Scaffolding module loaded. This leads to an ambiguous match error.
            // We can avoid this by finding that specific command using another Get-Command call.
            // Without this hack, you don't get tab-completion on scaffolder parameter names after a VS restart.
            if (string.Equals(command, "Invoke-Scaffolder", StringComparison.OrdinalIgnoreCase)) {
                var commandInfoPsObject = _invokeCommand.InvokeScript("Get-Command T4Scaffolding\\Invoke-Scaffolder");
                return (CommandInfo)commandInfoPsObject.First().BaseObject;
            }

            return _invokeCommand.GetCommand(command, commandTypes);
        }
示例#39
0
 public int Execute(CommandTypes commandType, Arguments args)
 {
     switch (commandType)
     {
         case CommandTypes.Add:
             return (Add(args));
         case CommandTypes.Sub:
             return (Sub(args));
         case CommandTypes.Mul:
             return (Mul(args));
         case CommandTypes.Div:
             return (Div(args));
         default:
             throw new InvalidOperationException();
     }
 }
示例#40
0
 public CommandMetadata(CommandMetadata other)
 {
     this._commandName = string.Empty;
     this._defaultParameterSetName = "__AllParameterSets";
     this._positionalBinding = true;
     this._helpUri = string.Empty;
     this._remotingCapability = System.Management.Automation.RemotingCapability.PowerShell;
     this._confirmImpact = System.Management.Automation.ConfirmImpact.Medium;
     this._otherAttributes = new Collection<Attribute>();
     if (other == null)
     {
         throw PSTraceSource.NewArgumentNullException("other");
     }
     this._commandName = other._commandName;
     this._confirmImpact = other._confirmImpact;
     this._defaultParameterSetFlag = other._defaultParameterSetFlag;
     this._defaultParameterSetName = other._defaultParameterSetName;
     this._implementsDynamicParameters = other._implementsDynamicParameters;
     this._supportsShouldProcess = other._supportsShouldProcess;
     this._supportsPaging = other._supportsPaging;
     this._supportsTransactions = other._supportsTransactions;
     this.CommandType = other.CommandType;
     this._wrappedAnyCmdlet = other._wrappedAnyCmdlet;
     this._wrappedCommand = other._wrappedCommand;
     this._wrappedCommandType = other._wrappedCommandType;
     this._parameters = new Dictionary<string, ParameterMetadata>(other.Parameters.Count, StringComparer.OrdinalIgnoreCase);
     if (other.Parameters != null)
     {
         foreach (KeyValuePair<string, ParameterMetadata> pair in other.Parameters)
         {
             this._parameters.Add(pair.Key, new ParameterMetadata(pair.Value));
         }
     }
     if (other._otherAttributes == null)
     {
         this._otherAttributes = null;
     }
     else
     {
         this._otherAttributes = new Collection<Attribute>(new List<Attribute>(other._otherAttributes.Count));
         foreach (Attribute attribute in other._otherAttributes)
         {
             this._otherAttributes.Add(attribute);
         }
     }
     this.staticCommandParameterMetadata = null;
 }
示例#41
0
文件: Command.cs 项目: rtownsend/cash
        /// <summary>
        /// Create a new command with type Type and path (with arguments) Cmd.
        /// </summary>
        /// <param name="Type">
        /// The enumeration representing what the command's purpose is <see cref="CommandTypes"/>
        /// </param>
        /// <param name="Cmd">
        /// The command (plus arguments) used. <see cref="System.String"/>
        /// </param>
        public Command(CommandTypes Type, string Cmd)
        {
            string[] Input = Cmd.Split(' ');
            CommandText = Input[0].Trim();

            if(Input.Length > 1)
            {
                Arguments = "";
                for(int i=1; i<Input.Length-1; i++)
                {
                    Arguments+= Input[i] + " ";
                }
                Arguments += Input[Input.Length-1];
            }

            CommandType = Type;
        }
 void handleButtonPressed(object sender, CommandTypes buttonType)
 {
     switch (buttonType)
     {
         case CommandTypes.EJECT:
             if (!isToggledSuspended)
                 gameInputBridge.eject();
                 break;
         case CommandTypes.QUIT:
             isToggledSuspended = !isToggledSuspended;
             break;
         case CommandTypes.SPLIT:
             if (!isToggledSuspended)
                 gameInputBridge.split();
             break;
         case CommandTypes.SUSPEND:
             if (!isToggledSuspended)
                 isSuspended = true;
             break;
     }
 }
示例#43
0
文件: PSSQMAPI.cs 项目: nickchal/pash
        public static void IncrementData(CommandTypes cmdType)
        {
            if (!isWinSQMEnabled)
            {
                return;
            }
            PSSqmDataPoint cmdlet = PSSqmDataPoint.Cmdlet;
            CommandTypes types = cmdType;
            if (types <= CommandTypes.ExternalScript)
            {
                switch (types)
                {
                    case CommandTypes.Alias:
                        cmdlet = PSSqmDataPoint.Alias;
                        goto Label_008B;

                    case CommandTypes.Function:
                        cmdlet = PSSqmDataPoint.Function;
                        goto Label_008B;

                    case (CommandTypes.Function | CommandTypes.Alias):
                        return;

                    case CommandTypes.Filter:
                        cmdlet = PSSqmDataPoint.Filter;
                        goto Label_008B;

                    case CommandTypes.Cmdlet:
                        cmdlet = PSSqmDataPoint.Cmdlet;
                        goto Label_008B;

                    case CommandTypes.ExternalScript:
                        cmdlet = PSSqmDataPoint.ExternalScript;
                        goto Label_008B;
                }
                return;
            }
            if (types != CommandTypes.Application)
            {
                if (types != CommandTypes.Script)
                {
                    if (types != CommandTypes.Workflow)
                    {
                        return;
                    }
                    cmdlet = PSSqmDataPoint.Function;
                }
                else
                {
                    cmdlet = PSSqmDataPoint.Script;
                }
            }
            else
            {
                cmdlet = PSSqmDataPoint.Application;
            }
        Label_008B:
            IncrementDataPoint((int) cmdlet);
        }
示例#44
0
 public void setCurrCmdTypeAndAppendCmdName(CommandTypes newCmdType, string newCmdName)
 {
     setCurrCmdType(newCmdType);
     appendCurrCmdName(newCmdName);
 }
示例#45
0
 public void setCurrCmdType(CommandTypes newCmdType)
 {
     currCommand.cmdType = newCmdType;
     //System.Console.WriteLine("currCommand.cmdType = {0}", currCommand.cmdType);
 }
示例#46
0
        public void resetBlockType()
        {
            prevBlockType = currCommand.cmdType;
            prevBlockText = currBlockText;
            currCommand.cmdType = CommandTypes.Unknown;
            currBlockText = new StringBuilder();

            prevToken = "";
            token = "";

            currCommand.action = "";
            currCommand.baseCmdName = "";
            currCommand.cmdName = "";
            currCommand.objectName = "";
            currCommand.alterType = "";
            currCommand.secondaryObjectName = "";
            currCommand.secondaryCmdName = "";
            currCommand.syntaxErrorFound = false;

            tokenCountWithoutComments = 0;
            blockStartLine = -1;

            autodetectMode = AutodetectMode.Normal;
            detourTaken = 0;
            detourStart = -1;
            detourPath = "";
        }
示例#47
0
        private void checkForAndBeginDetour(int detourStartsAtToken, CommandTypes cmdTypeBefore, String actionBefore, String baseCmdNameBefore, String detourStartsWithToken, String detourUniqueName)
        {
            int tokenCountWithoutCommentsAndDetour = tokenCountWithoutComments - detourTaken;
            string upperToken = token.ToUpper();

            if (tokenCountWithoutCommentsAndDetour == detourStartsAtToken &&
            currCommand.cmdType == cmdTypeBefore &&
            currCommand.action == actionBefore &&
            currCommand.baseCmdName == baseCmdNameBefore &&
            upperToken == detourStartsWithToken)
            {
            autodetectMode = AutodetectMode.Detour;
            detourStart = tokenCountWithoutComments;
            detourPath = detourUniqueName;
            }
        }
        // Processes a string into the properties of the current instance.
        // Specification of a string:
        // Type<t>::Target<tgt>::Content<cont>::Origin<orig>;
        private void SetCommandByString(string command)
        {
            // Split the string at the delimiter ::
            string[] parts = command.Split(new string[] { "::" }, StringSplitOptions.None);

            // Set the type
            if (parts.Length == 4)
            {
                // Set the command type.
                switch (parts[0].Substring(5, parts[0].Length - 6))
                {
                    case "A-A":
                        Type = CommandTypes.Arduino_To_Arduino;
                        break;
                    case "A-I":
                        Type = CommandTypes.Arduino_To_Interface;
                        break;
                    case "I-A":
                        Type = CommandTypes.Interface_To_Arduino;
                        break;
                    case "A-B":
                        Type = CommandTypes.Arduino_Broadcast;
                        break;
                    case "I-B":
                        Type = CommandTypes.Interface_Broadcast;
                        break;
                    default:
                        _isFaulty = true;
                        break;
                }

                // Set strings by Substring functions and trimm them.
                Target = parts[1].Substring(7, parts[1].Length - 8).Trim();
                Content = parts[2].Substring(8, parts[2].Length - 9).Trim();
                Origin = parts[3].Substring(7, parts[3].Length - 9).Trim();
            }
        }
示例#49
0
文件: CommandInfo.cs 项目: mauve/Pash
 internal CommandInfo(string name, CommandTypes type)
 {
     CommandType = type;
     Name = name;
 }
示例#50
0
 //tries to locate and set a switch value
 private void _TryLocateSwitch(string key, CommandTypes value)
 {
     if (this._CommandType == CommandTypes.TooManyCommands) return;
     if (this.HasSwitch(key)) this._CommandType = value;
 }
示例#51
0
 private static CommandInfo TryNormalSearch(string commandName, ExecutionContext context, CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes commandTypes, ref Exception lastError)
 {
     CommandInfo current = null;
     CommandSearcher searcher = new CommandSearcher(commandName, searchResolutionOptions, commandTypes, context) {
         CommandOrigin = commandOrigin
     };
     try
     {
         if (!searcher.MoveNext())
         {
             if (!commandName.Contains("-") && !commandName.Contains(@"\"))
             {
                 discoveryTracer.WriteLine("The command [{0}] was not found, trying again with get- prepended", new object[] { commandName });
                 commandName = "get" + '-' + commandName;
                 try
                 {
                     current = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context);
                 }
                 catch (CommandNotFoundException)
                 {
                 }
             }
             return current;
         }
         current = searcher.Current;
     }
     catch (ArgumentException exception)
     {
         lastError = exception;
     }
     catch (PathTooLongException exception2)
     {
         lastError = exception2;
     }
     catch (FileLoadException exception3)
     {
         lastError = exception3;
     }
     catch (FormatException exception4)
     {
         lastError = exception4;
     }
     catch (MetadataException exception5)
     {
         lastError = exception5;
     }
     return current;
 }
示例#52
0
 private static CommandInfo TryModuleAutoDiscovery(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes commandTypes, ref Exception lastError)
 {
     CommandInfo info = null;
     try
     {
         CmdletInfo cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-Module");
         if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
         {
             cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
             if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
             {
                 discoveryTracer.WriteLine("Executing non module-qualified search: {0}", new object[] { commandName });
                 context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
                 foreach (string str in ModuleUtils.GetDefaultAvailableModuleFiles(true, true, context))
                 {
                     string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(str);
                     Dictionary<string, List<CommandTypes>> dictionary = AnalysisCache.GetExportedCommands(str, false, context);
                     if (dictionary != null)
                     {
                         if (dictionary.ContainsKey(commandName))
                         {
                             CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context) {
                                 Visibility = cmdlet.Visibility
                             };
                             Command command = new Command(commandInfo);
                             discoveryTracer.WriteLine("Found in module: {0}", new object[] { str });
                             PowerShell shell = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("PassThru").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false);
                             Collection<PSModuleInfo> collection = null;
                             try
                             {
                                 collection = shell.Invoke<PSModuleInfo>();
                             }
                             catch (Exception exception)
                             {
                                 discoveryTracer.WriteLine("Encountered error importing module: {0}", new object[] { exception.Message });
                                 lastError = exception;
                                 CommandProcessorBase.CheckForSevereException(exception);
                             }
                             if ((collection == null) || (collection.Count == 0))
                             {
                                 string resourceStr = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportMatchingModule, commandName, fileNameWithoutExtension);
                                 CommandNotFoundException exception2 = new CommandNotFoundException(originalCommandName, lastError, "CouldNotAutoloadMatchingModule", resourceStr, new object[0]);
                                 throw exception2;
                             }
                             info = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context);
                         }
                         if (info != null)
                         {
                             return info;
                         }
                     }
                 }
             }
             return info;
         }
         return info;
     }
     catch (CommandNotFoundException)
     {
         throw;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
     }
     finally
     {
         context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
     }
     return info;
 }
示例#53
0
        internal static CommandInfo LookupCommandInfo(string commandName, CommandTypes commandTypes, SearchResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context)
        {
            if (string.IsNullOrEmpty(commandName))
            {
                return null;
            }
            CommandInfo result = null;
            string command = commandName;
            Exception lastError = null;
            CommandLookupEventArgs e = null;
            EventHandler<CommandLookupEventArgs> preCommandLookupAction = context.EngineIntrinsics.InvokeCommand.PreCommandLookupAction;
            if (preCommandLookupAction != null)
            {
                discoveryTracer.WriteLine("Executing PreCommandLookupAction: {0}", new object[] { commandName });
                try
                {
                    context.CommandDiscovery.RegisterLookupCommandInfoAction("ActivePreLookup", command);
                    e = new CommandLookupEventArgs(command, commandOrigin, context);
                    preCommandLookupAction(command, e);
                    discoveryTracer.WriteLine("PreCommandLookupAction returned: {0}", new object[] { e.Command });
                }
                catch (Exception exception2)
                {
                    CommandProcessorBase.CheckForSevereException(exception2);
                }
                finally
                {
                    context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActivePreLookup", commandName);
                }
            }
            if ((e == null) || !e.StopSearch)
            {
                discoveryTracer.WriteLine("Looking up command: {0}", new object[] { commandName });
                result = TryNormalSearch(commandName, context, commandOrigin, searchResolutionOptions, commandTypes, ref lastError);
                if (result == null)
                {
                    PSModuleAutoLoadingPreference preference = GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                    if (preference != PSModuleAutoLoadingPreference.None)
                    {
                        result = TryModuleAutoLoading(commandName, context, command, commandOrigin, result, ref lastError);
                    }
                    if (result == null)
                    {
                        if (preference == PSModuleAutoLoadingPreference.All)
                        {
                            result = TryModuleAutoDiscovery(commandName, context, command, commandOrigin, searchResolutionOptions, commandTypes, ref lastError);
                        }
                        if (result == null)
                        {
                            result = InvokeCommandNotFoundHandler(commandName, context, command, commandOrigin, result);
                        }
                    }
                }
            }
            else if (e.Command != null)
            {
                result = e.Command;
            }
            if (result != null)
            {
                EventHandler<CommandLookupEventArgs> postCommandLookupAction = context.EngineIntrinsics.InvokeCommand.PostCommandLookupAction;
                if (postCommandLookupAction != null)
                {
                    discoveryTracer.WriteLine("Executing PostCommandLookupAction: {0}", new object[] { command });
                    try
                    {
                        context.CommandDiscovery.RegisterLookupCommandInfoAction("ActivePostCommand", command);
                        e = new CommandLookupEventArgs(command, commandOrigin, context) {
                            Command = result
                        };
                        postCommandLookupAction(command, e);
                        if (e != null)
                        {
                            result = e.Command;
                            discoveryTracer.WriteLine("PreCommandLookupAction returned: {0}", new object[] { e.Command });
                        }
                    }
                    catch (Exception exception3)
                    {
                        CommandProcessorBase.CheckForSevereException(exception3);
                    }
                    finally
                    {
                        context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActivePostCommand", command);
                    }
                }
            }
            if (result == null)
            {
                discoveryTracer.TraceError("'{0}' is not recognized as a cmdlet, function, operable program or script file.", new object[] { commandName });
                CommandNotFoundException exception4 = new CommandNotFoundException(command, lastError, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);

				throw exception4;
            }
            return result;
        }
 // Sets the command to a faulty state
 private void setFaulty()
 {
     Type = CommandTypes.Faulty;
     Target = "unknown";
     Content = "none";
     Origin = "unknown";
 }
示例#55
0
 public void TypeTest()
 {
     ICommand target = CreateICommand(); // TODO: Initialize to an appropriate value
     CommandTypes expected = new CommandTypes(); // TODO: Initialize to an appropriate value
     CommandTypes actual;
     target.Type = expected;
     actual = target.Type;
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
示例#56
0
 public ActionDetectedEventArgs(CommandTypes t, Student student)
 {
     this.CommandType = t;
      this.Student = student;
 }
 public IEnumerable<CommandInfo> GetCommands(string name, CommandTypes commandTypes, bool nameIsPattern)
 {
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     CommandSearcher iteratorVariable0 = new CommandSearcher(name, nameIsPattern ? (SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveFunctionPatterns | SearchResolutionOptions.ResolveAliasPatterns) : SearchResolutionOptions.None, commandTypes, this._context);
 Label_0066:
     try
     {
         if (!iteratorVariable0.MoveNext())
         {
             goto Label_00C2;
         }
     }
     catch (ArgumentException)
     {
         goto Label_0066;
     }
     catch (PathTooLongException)
     {
         goto Label_0066;
     }
     catch (FileLoadException)
     {
         goto Label_0066;
     }
     catch (MetadataException)
     {
         goto Label_0066;
     }
     catch (FormatException)
     {
         goto Label_0066;
     }
     CommandInfo current = ((IEnumerator) iteratorVariable0).Current as CommandInfo;
     if (current != null)
     {
         yield return current;
     }
     goto Label_0066;
 Label_00C2:;
 }
示例#58
0
        private bool doCourseRegistrationAction(SemanticValueDict semantics, CommandTypes cmd)
        {
            bool callEvent = false;
             IAction action = cmd.GetAction();
             if (currentWorkingAction == null || !currentWorkingAction.GetType().Equals(action.GetType()))
             {
            currentWorkingAction = action;
             }
             else if (currentWorkingAction.GetType().Equals(action.GetType()) || currentWorkingAction is UnknownAction)
             {
            action.Inform(currentWorkingAction.Semantics, CurrStudent);
            currentWorkingAction = action;
             }
             callEvent = InformAndPerformCurrentAction(semantics);

             return callEvent;
        }
 public CommandInfo GetCommand(string commandName, CommandTypes type)
 {
     CommandInfo info = null;
     try
     {
         CommandOrigin runspace = CommandOrigin.Runspace;
         if (this._cmdlet != null)
         {
             runspace = this._cmdlet.CommandOrigin;
         }
         info = CommandDiscovery.LookupCommandInfo(commandName, type, SearchResolutionOptions.None, runspace, this._context);
     }
     catch (CommandNotFoundException)
     {
     }
     return info;
 }
示例#60
0
 public void ParseCommandTypeTest()
 {
     ICommand target = CreateICommand(); // TODO: Initialize to an appropriate value
     string commandName = string.Empty; // TODO: Initialize to an appropriate value
     CommandTypes expected = new CommandTypes(); // TODO: Initialize to an appropriate value
     CommandTypes actual;
     actual = target.ParseCommandType(commandName);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }