public void Command_GivenACommand_ReturnedFailedResult()
        {
            var c      = new Command.Command();
            var result = c.DoCommand(new[] { "Explore here" });

            Assert.IsFalse(result.Successful);
        }
Example #2
0
 public void SetOrder(Command command)
 {
     if (command.ToString() == "Command.BakeChickenWingCommand")
     {
         Console.WriteLine("服务员:鸡翅没有了,请点别的烧烤。");
     }
     else
     {
         orders.Add(command);
         Console.WriteLine("增加订单:{0} 时间:{1}", command, DateTime.Now.ToString());
     }
 }
Example #3
0
        public RemoteControl()
        {
            this.onCommands = new Command[7];
            this.offCommands = new Command[7];

            Command noCommand = new NoCommand();
            for (int i = 0; i < 7; i++)
            {
                this.onCommands[i] = noCommand;
                this.offCommands[i] = noCommand;
            }
            this.undoCommand = new NoCommand();
        }
Example #4
0
 /// <summary>
 /// Registers the specified Command instance.
 /// </summary>
 public void Add(Command cmd)
 {
     if(_commands.ContainsKey(cmd.Name)) {
         throw new ArgumentException(string.Format("A command has already been " +
                     "registered with the name {0} (in class {1})", cmd.Name, cmd.Type));
     }
     _commands.Add(cmd.Name, cmd);
     if(cmd.Alias != null) {
         if(!_commands.ContainsKey(cmd.Alias)) {
             _commands.Add(cmd.Alias, cmd);
         }
         else {
             _log.WarnFormat("Attempt to register command {0} under alias {1} failed; " +
                     "alias is already registered", cmd.Name, cmd.Alias);
         }
     }
 }
Example #5
0
        public void TryToWithdrawMoreThanBalance_ShouldFail()
        {
            var account = new Account();

            var command = new Command.Command {
                Amount = 100, TheAction = Action.Deposit
            };

            account.Process(command);

            command = new Command.Command {
                Amount = 150, TheAction = Action.Withdraw
            };
            account.Process(command);

            Assert.That(account.Balance, Is.EqualTo(100));
            Assert.IsFalse(command.Success);
        }
Example #6
0
        /// <summary>
        /// Validates the first positional parameter, verifying it is either
        /// the path to a command file, or one of the registered commands.
        /// If it is a command, we dynamically update our command-line definition
        /// to include any additional parameters needed by the specified command.
        /// </summary>
        protected bool ValidateCommand(Argument arg, string argVal, out string errorMsg)
        {
            bool ok;

            errorMsg = String.Format("Command file '{0}' not found", argVal);
            if (_commands.Contains(argVal))
            {
                ok = true;

                // Mark the argument as a command
                ((PositionalArgument)arg).IsCommand = true;

                // Add command arguments as keyword args
                Command.Command cmd = _commands[argVal];

                // First, add any args for commands that must be invoked before the
                // requested command, such as SetLogonInfo, OpenApplication, etc
                foreach (var i in _context.FindPathToType(cmd.Type, cmd))
                {
                    if (i.IsCommand)
                    {
                        AddCommandParamsAsArgs(i.Command);
                    }
                }

                // Now add arguments for the command requested
                AddCommandParamsAsArgs(cmd);
            }
            else
            {
                ok = File.Exists(argVal);
                if (ok)
                {
                    var logArg = _cmdLine.AddPositionalArgument("LogFile", "Path to log file",
                                                                (_, logFile) => Log(null, logFile));
                    logArg.IsRequired = false;
                    // Instruct parser to include unrecognised args, since these
                    // will be treated as variable assignments
                    _cmdLine.Definition.IncludeUnrecognisedKeywordArgs = true;
                    _cmdLine.Definition.IncludeUnrecognisedFlagArgs    = true;
                }
            }
            return(ok);
        }
Example #7
0
        private static Command.Command GetAckCommand(
            Command.Command command,
            byte?target         = null,
            long?id             = null,
            Operation?operation = null,
            int?pin             = null,
            int?value           = null
            )
        {
            var ackCommand = new Command.Command
            {
                Id        = id ?? command.Id,
                Operation = operation ?? command.Operation,
                Pin       = pin ?? command.Pin,
                Value     = value ?? -1,
                Target    = target ?? command.Target
            };

            return(ackCommand);
        }
Example #8
0
 /// Add additional arguments needed by the command
 protected void AddCommandParamsAsArgs(Command.Command cmd)
 {
     _log.TraceFormat("Adding command-line args for {0} command", cmd.Name);
     foreach (var param in cmd.Parameters)
     {
         _log.DebugFormat("Processing param {0}", param);
         if (param.IsSettingsCollection)
         {
             _log.DebugFormat("Processing collection type {0}", param.ParameterType);
             // Get individual settings from collection and add them
             foreach (var setting in _commands.GetSettings(param.ParameterType))
             {
                 AddSettingAsArg(setting);
             }
         }
         else if (param.HasParameterAttribute)
         {
             AddSettingAsArg(param);
         }
     }
 }
Example #9
0
        public void DepositAndWithdraw()
        {
            var account = new Account();

            var command = new Command.Command {
                Amount = 100, TheAction = Action.Deposit
            };

            account.Process(command);

            Assert.That(account.Balance, Is.EqualTo(100));
            Assert.IsTrue(command.Success);

            command = new Command.Command {
                Amount = 50, TheAction = Action.Withdraw
            };
            account.Process(command);

            Assert.That(account.Balance, Is.EqualTo(50));
            Assert.IsTrue(command.Success);
        }
Example #10
0
        static void Main(string[] args)
        {
            // creates a queue of commands and executes it when you deem appropriate
            // example: ICommand, undo/redo functionality. for each action, an inverse action
            // is a pushed onto a stack and popped when the appropriate button is clicked
            // CQRS uses the command pattern
            // https://en.wikipedia.org/wiki/Command_pattern

            var command = new Command();
            //command.CanExecuteChanged += (sender, eventArgs) => Console.WriteLine("Action added.");
            command.Add(() => Console.WriteLine("I'm creating an action."));
            command.Add(() => Console.WriteLine("But it's not getting executed just yet."));
            command.Add(() => Console.WriteLine("For that I need to process the queue."));
            command.Add(() => Console.WriteLine("Voila, done!"));

            Console.WriteLine("Executing commands sequentially:");
            command.Execute(true);
            Console.WriteLine();
            Console.WriteLine("Executing commands in parallell:");
            command.Execute(false);
            Console.ReadLine();
        }
Example #11
0
        private static void BeginSend(this AckState ackState)
        {
            ackState.TryAndLog(
                ack =>
            {
                AckQueueDictionary.AddOrUpdate(
                    ack.RemoteEndPoint,
                    key => ack.Queue,
                    (key, current) =>
                {
                    current.CompleteAdding();
                    return(ack.Queue);
                }
                    );
                while (!ack.Queue.IsCompleted)
                {
                    var command = ack.Queue.Take();
                    Command.Command ackCommand;
                    try
                    {
                        switch (command.Operation)
                        {
                        case Operation.Connect:
                            ackCommand = GetAckCommand(
                                command,
                                value: 1
                                );
                            break;

                        case Operation.WiringPiSetupPiFace:
                            ackCommand = GetAckCommand(
                                command,
                                value: PiFace.WiringPiSetupPiFace()
                                );
                            break;

                        case Operation.PullUpDnControl:
                            ackCommand = GetAckCommand(
                                command,
                                value: PiFace.PullUpDnControl(command.Pin, command.Value)
                                );
                            break;

                        case Operation.DigitalWrite:
                            ackCommand = GetAckCommand(
                                command,
                                value: PiFace.DigitalWrite(command.Pin, command.Value)
                                );
                            break;

                        case Operation.DigitalRead:
                            ackCommand = GetAckCommand(
                                command,
                                value: PiFace.DigitalRead(command.Pin)
                                );
                            break;

                        case Operation.MonitorInput:
                            var monitor = MonitorInputDictionary.AddOrUpdate(
                                ackState.RemoteEndPoint,
                                key =>
                            {
                                var value          = new Command.Command[8];
                                value[command.Pin] = command;
                                return(value);
                            },
                                (key, value) =>
                            {
                                value[command.Pin] = command;
                                return(value);
                            }
                                );
                            var result = monitor[command.Pin];
                            ackCommand = GetAckCommand(
                                command,
                                value: (result.Id == command.Id && command.Value == result.Value)
                                                   ? 1
                                                   : 0
                                );
                            if (PiFace.InputChanged == null)
                            {
                                PiFace.InputChanged = MonitorInputChanged;
                            }
                            break;

                        case Operation.MonitorInputChanged:
                            ackCommand = command;
                            break;

                        // ReSharper disable RedundantCaseLabel
                        case Operation.None:
                        default:
                            // ReSharper restore RedundantCaseLabel
                            ackCommand = GetAckCommand(
                                command,
                                operation: Operation.None,
                                value: PiFace.DigitalRead(command.Pin)
                                );
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.LogException();
                        ackCommand = GetAckCommand(
                            command,
                            value: -1
                            );
                    }

                    var ackCommandBytes = ackCommand.ToArray();
                    Log.Info(
                        "Sending {0} bytes from {1} connected to {2}",
                        ackCommandBytes.Length,
                        ack.Handler.LocalEndPoint,
                        ack.Handler.RemoteEndPoint
                        );
                    ackState.Handler.BeginSend(
                        ackCommandBytes,
                        0,
                        ackCommandBytes.Length,
                        0,
                        ackState.SendCallback,
                        null
                        );
                }
            }
                );
        }
Example #12
0
 public void SetSave(Command Guardado)
 {
     this.Guardo = Guardado;
 }
Example #13
0
 internal Invoker(Command cmd)
 {
     this.cmd = cmd;
 }
Example #14
0
 public void OffButtonWasPushed(int slot)
 {
     this.offCommands[slot].Execute();
     this.undoCommand = offCommands[slot];
 }
Example #15
0
 public void CancelOrder(Command command)
 {
     _commands.Remove(command);
     Console.WriteLine("取消订单:{0},时间:{1}", command.ToString(), DateTime.Now.ToString());
 }
Example #16
0
        /// Invoke an instance of the supplied Command object, using the supplied
        /// arguments dictionary to obtain parameter values. An instance of the
        /// host object must already be available in the context.
        private object InvokeCommand(Command cmd, Dictionary<string, object> args)
        {
            if(!HasObject(cmd.Type)) {
                throw new ContextException(String.Format("No object of type {0} " +
                            "is available in the current context", cmd.Type));
            }

            string paramLog;
            object[] parms = null;
            try {
                parms = PrepareCommandArguments(cmd, args, out paramLog);
            }
            catch(Exception ex) {
                throw new CommandException("An error occurred while preparing arguments for command {0}", cmd.Name, ex);
            }

            if(paramLog.Length > 0) {
                _log.InfoFormat("Executing {0} command {1}:{2}", cmd.Type.Name, cmd.Name, paramLog);
            }
            else {
                _log.InfoFormat("Executing {0} command {1}...", cmd.Type.Name, cmd.Name);
            }

            // Execute the method corresponding to this command
            var ctxt = this[cmd.Type];
            object result;
            try {
                result = cmd.MethodInfo.Invoke(ctxt, parms);
            }
            catch(TargetInvocationException ex) {
                throw new CommandException("Command {0} threw an exception:", cmd.Name,
                        ex.InnerException != null ? ex.InnerException : ex);
            }

            // If the method is a factory method, set the returned object in the context
            if(result != null && cmd.IsFactory) {
                Set(result);
            }

            return result;
        }
 public void SetCommand(int i, Command onCommand, Command offCommand)
 {
     onCommands.Insert(i, onCommand);
     offCommands.Insert(i, offCommand);
 }
Example #18
0
 public void SetCommand(Command command)
 {
     this._command = command;
 }
Example #19
0
        /// <summary>
        /// Registers commands and factories from the supplied class.
        /// Commands must be tagged with the attribute Command to be locatable.
        /// </summary>
        public void RegisterClass(Type t)
        {
            Factory factory;
            Command cmd;

            if(t.IsClass) {
                // Process class level attributes
                List<SettingAttribute> settings = new List<SettingAttribute>();
                foreach(var attr in t.GetCustomAttributes(typeof(SettingAttribute), false)) {
                    if(attr is DynamicSettingAttribute) {
                        // Verify that DynamicSettingAttributes are only used on IDynamicSettingsCollection
                        if(t.GetInterface("IDynamicSettingsCollection") == null) {
                            throw new ArgumentException(string.Format("A DynamicSettingAttribute has " +
                                        "been defined on class {0}, but this class does not implement " +
                                        "the IDynamicSettingsCollection interface", t.Name));
                        }
                    }
                    settings.Add((SettingAttribute)attr);
                }
                // Attributes are returned in random order, so sort by preferred order
                settings.Sort((a, b) => (a.SortKey).CompareTo(b.SortKey));
                _settings[t] = settings;

                // Process members of class
                foreach(var mi in t.GetMembers(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly)) {
                    cmd = null;
                    factory = null;
                    foreach(var attr in mi.GetCustomAttributes(false)) {
                        if(attr is CommandAttribute) {
                            cmd = new Command(t, mi as MethodInfo, attr as CommandAttribute);
                            Add(cmd);
                        }
                        if(attr is FactoryAttribute) {
                            factory = new Factory(mi, attr as FactoryAttribute);
                            Add(factory);
                        }
                    }
                    if(cmd != null && factory != null) {
                        cmd._factory = factory;
                        factory._command = cmd;
                    }
                }
            }
        }
Example #20
0
 public void CancelOrder(Command command)
 {
     orders.Remove(command);
     Console.WriteLine("取消订单:{0} 时间:{1}", command, DateTime.Now.ToString(CultureInfo.InvariantCulture));
 }
 public void OnButtonWasPressed(int i)
 {
     onCommands[i].Execute();
     undoCommand = offCommands[i];
 }
Example #22
0
 public void SetCommand(Command command)
 {
     _command = command;
 }
Example #23
0
        /// <summary>
        /// Determines the sequence of command invocations, property accesses,
        /// and constructor calls that are required to instantiate an object of
        /// the requested type, given the current state of the context.
        /// </summary>
        /// <returns>A Stack containing the methods/properties/ctors to be invoked
        /// to create an instance of the desire type. The stack may be empty if an
        /// object of the desired type is already available.
        /// </returns>
        /// <exception>Throws ContextException if an object of the desired type
        /// cannot be created from the current context.
        /// </exception>
        public Stack<Factory> FindPathToType(Type t, Command cmd)
        {
            var steps = new Stack<Factory>();
            _log.TraceFormat("Determining steps needed to create an instance of {0}", t);

            // Create a lambda for recursion
            Action<Type> scan = null;
            scan = type => {
                if(!HasObject(type)) {
                    // See if we can get an instance from what we do have
                    if(_registry.Contains(type)) {
                        Factory factory = _registry.GetFactory(type);
                        _log.DebugFormat("Found {0} on {1}", factory, factory.DeclaringType);
                        steps.Push(factory);
                        if(factory.IsConstructor) {
                            // Determine steps needed to obtain instances of
                            // constructor arguments (if any)
                            foreach(var param in factory.Constructor.GetParameters()) {
                                scan(param.ParameterType);
                            }
                        }
                        else {
                            // Determine how to obtain an instance of the item
                            // holding the factory method/property
                            scan(factory.DeclaringType);
                        }
                    }
                    else {
                        throw new ContextException(string.Format("No method, property, or constructor " +
                                    "is registered as a Factory for {0} objects, which are required by " +
                                    "{1}", type, cmd.Name));
                    }
                }
            };
            scan(t);
            return steps;
        }
Example #24
0
 private ISettingsCollection PrepareSettingsCollectionArg(Command cmd, CommandParameter param,
         Dictionary<string, object> args, StringBuilder sb)
 {
     // Attempt to create an instance of the collection class if necessary
     if(!HasObject(param.ParameterType)) {
         foreach(var step in FindPathToType(param.ParameterType, cmd)) {
             Instantiate(step, args);
         }
     }
     // Set each setting that has a value in the supplied args
     var coll = this[param.ParameterType] as ISettingsCollection;
     foreach(var setting in GetSettings(param.ParameterType)) {
         if(setting is DynamicSettingAttribute) {
             _log.Trace("Retrieving dynamic setting argument names");
             foreach(var dynset in ((IDynamicSettingsCollection)coll).DynamicSettingNames) {
                 if(args.ContainsKey(dynset)) {
                     _log.DebugFormat("Processing dynamic setting {0}", dynset);
                     coll[dynset] = ConvertSetting(args[dynset], setting);
                     LogSettingNameValue(sb, dynset, coll[dynset]);
                 }
             }
         }
         else if(args.ContainsKey(setting.Name)) {
             coll[setting.InternalName] = ConvertSetting(args[setting.Name], setting);
             LogSettingValue(sb, setting, coll[setting.InternalName]);
         }
         else if(setting.HasAlias && args.ContainsKey(setting.Alias)) {
             coll[setting.InternalName] = ConvertSetting(args[setting.Alias], setting);
             LogSettingValue(sb, setting, coll[setting.InternalName]);
         }
     }
     return coll;
 }
Example #25
0
        /// Prepares the parameters to be passed to a command.
        private object[] PrepareCommandArguments(Command cmd, Dictionary<string, object> args, out string paramLog)
        {
            // Create an array of parameters in the order expected
            var parms = new object[cmd.Parameters.Count];
            var sb = new StringBuilder();
            var i = 0;

            foreach(var param in cmd.Parameters) {
                _log.TraceFormat("Processing parameter {0}", param.Name);
                if(args.ContainsKey(param.Name)) {
                    parms[i] = ConvertSetting(args[param.Name], param);
                    LogSettingValue(sb, param, parms[i]);
                }
                else if(param.HasAlias && args.ContainsKey(param.Alias)) {
                    parms[i] = ConvertSetting(args[param.Alias], param);
                    LogSettingValue(sb, param, parms[i]);
                }
                else if(param.IsSettingsCollection) {
                    parms[i] = PrepareSettingsCollectionArg(cmd, param, args, sb);
                }
                else if(param.HasDefaultValue) {
                    // Deal with missing arg values, default values, etc
                    _log.DebugFormat("No value supplied for {0}; using default value '{1}'",
                            param.Name, param.DefaultValue);
                    parms[i] = param.DefaultValue;
                    LogSettingValue(sb, param, parms[i]);
                }
                else if(HasObject(param.ParameterType)) {
                    parms[i] = this[param.ParameterType];
                    if(param.HasParameterAttribute) {
                        LogSettingValue(sb, param, parms[i]);
                    }
                }
                // If there is a factory to create this type, then try to create it
                else if(_registry.Contains(param.ParameterType)) {
                    foreach(var step in FindPathToType(param.ParameterType, cmd)) {
                        Instantiate(step, args);
                    }
                    parms[i] = this[param.ParameterType];
                    if(param.HasParameterAttribute) {
                        LogSettingValue(sb, param, parms[i]);
                    }
                }
                else if(MissingArgHandler != null) {
                    object val = MissingArgHandler(param);
                    if(val != null) {
                        parms[i] = ConvertSetting(val, param);
                        LogSettingValue(sb, param, parms[i]);
                    }
                    else {
                        throw new ArgumentException(
                                String.Format("No value was specified for the required argument '{0}' to command '{1}'",
                                param.Name, cmd.Name));
                    }
                }
                else {
                    throw new ArgumentException(
                            String.Format("No value was specified for the required argument '{0}' to command '{1}'",
                            param.Name, cmd.Name));
                }
                i++;
            }
            paramLog = sb.ToString();
            return parms;
        }
Example #26
0
 public void AddCommand(Command command)
 {
     commands.Add(command);
 }
Example #27
0
 /// <summary>
 /// Checks if the supplied Dictionary contains all the required arguments
 /// to invoke the specified command.
 /// </summary>
 public static bool ContainsRequiredValuesForCommand(this Dictionary<string, object> args, Command cmd)
 {
     foreach(var param in cmd.Parameters) {
         if(!args.ContainsValueForSetting(param)) {
             return false;
         }
     }
     return true;
 }
Example #28
0
 public void SetCommand(int slot,Command onCommand,Command offCommand)
 {
     this.onCommands[slot] = onCommand;
     this.offCommands[slot] = offCommand;
 }