Пример #1
0
        public void CanGetParameterFromAppSettingsAndConnectionStrings()
        {
            var invoker = new CommandInvoker("null", typeof(CanUseAppSetting), new Settings());

            var appSettings = new Dictionary<string, string>
            {
                {"my-setting", "my-value"}
            };

            var connectionStrings = new Dictionary<string, string>
            {
                {"my-conn", "my-value"}
            };

            var environmentVariables = new Dictionary<string, string>
            {
                {"my-env", "my-value"}
            };

            invoker.Invoke(Enumerable.Empty<Switch>(), new EnvironmentSettings(appSettings, connectionStrings, environmentVariables));

            var instance = (CanUseAppSetting)invoker.CommandInstance;

            Assert.That(instance.AppSetting, Is.EqualTo("my-value"));
            Assert.That(instance.ConnectionString, Is.EqualTo("my-value"));
            Assert.That(instance.EnvironmentVariable, Is.EqualTo("my-value"));
        }
Пример #2
0
 public void WhenCommandIsSentAndHandlerIsNotPresent_ExceptionThrown()
 {
     ObjectFactory.ResetDefaults();
     Mock<IDocumentSession> documentSessionMock = new Mock<IDocumentSession>();
     CommandInvoker invoker = new CommandInvoker(ObjectFactory.Container, documentSessionMock.Object);
     Assert.Throws<StructureMapException>(() => invoker.Execute("SomeString"));
 }
Пример #3
0
        public void WhenCommandIsSentAndHandlerIsPresent_SessionIsFlushed()
        {
            ObjectFactory.ResetDefaults();
            Mock<ICommandHandler<String>> mockHandler = new Mock<ICommandHandler<string>>();
            Mock<IDocumentSession> documentSessionMock = new Mock<IDocumentSession>();
            ObjectFactory.Configure(x => x.For<ICommandHandler<string>>().Use(mockHandler.Object));

            CommandInvoker invoker = new CommandInvoker(ObjectFactory.Container, documentSessionMock.Object);
            invoker.Execute("SomeString");
            documentSessionMock.Verify(x => x.SaveChanges(), Times.Once());
        }
Пример #4
0
        public void WhenCommandIsSentAndHandlerIsNotPresent_SessionIsNotFlushed()
        {
            ObjectFactory.ResetDefaults();
            Mock<IDocumentSession> documentSessionMock = new Mock<IDocumentSession>();
            CommandInvoker invoker = new CommandInvoker(ObjectFactory.Container, documentSessionMock.Object);

            try { invoker.Execute("SomeString"); }
            catch { }

            documentSessionMock.Verify(x => x.SaveChanges(), Times.Never());
        }
Пример #5
0
        public void CanCorrectlyHandleDifferentAlternativeSwitchFormatsFoundInOneSingleTokenOnly_Shortname(string switchText)
        {
            var settings = new Settings();
            var invoker = new CommandInvoker("bimse", settings, new Bimse());
            var arguments = Go.Parse(new[] { switchText }, settings);

            invoker.Invoke(arguments.Switches, EnvironmentSettings.Empty);

            var bimseInstance = (Bimse)invoker.CommandInstance;

            Assert.That(bimseInstance.Switch, Is.EqualTo("value2"));
        }
Пример #6
0
        public void WhenCommandIsSentAndHandlerIsPresentButExceptionIsThrown_SessionIsNotFlushed()
        {
            ObjectFactory.ResetDefaults();
            Mock<ICommandHandler<String>> mockHandler = new Mock<ICommandHandler<string>>();
            mockHandler.Setup(x => x.Handle(It.IsAny<string>())).Throws<Exception>();
            Mock<IDocumentSession> documentSessionMock = new Mock<IDocumentSession>();
            ObjectFactory.Configure(x => x.For<ICommandHandler<string>>().Use(mockHandler.Object));

            CommandInvoker invoker = new CommandInvoker(ObjectFactory.Container, documentSessionMock.Object);
            Assert.Throws<Exception>(() => invoker.Execute("SomeString"));
            documentSessionMock.Verify(x => x.SaveChanges(), Times.Never());
        }
Пример #7
0
        public void HandlerIsInvokedWhenCommandIsSent()
        {
            var kernel = new StandardKernel();

            var mockCommandHandler = new Mock<ICommandHandler<string>>();
            Mock<ISession> mockSession = CreateMockSession();
            kernel.Bind<ICommandHandler<string>>().ToConstant(mockCommandHandler.Object);

            var commandInvoker = new CommandInvoker(kernel, mockSession.Object);
            commandInvoker.Execute("nothing");

            mockCommandHandler.Verify(x => x.Handle("nothing"), Times.Once());
        }
Пример #8
0
        public void TransactionIsCommittedWhenCommandIsSent()
        {
            var kernel = new StandardKernel();

            var mockCommandHandler = new Mock<ICommandHandler<string>>();
            var mockSession = new Mock<ISession>();
            var mockTransaction = new Mock<ITransaction>();
            mockSession.Setup(x => x.BeginTransaction()).Returns(mockTransaction.Object);
            kernel.Bind<ICommandHandler<string>>().ToConstant(mockCommandHandler.Object);

            var commandInvoker = new CommandInvoker(kernel, mockSession.Object);
            commandInvoker.Execute("nothing");

            mockTransaction.Verify(x => x.Commit(), Times.Once());
        }
Пример #9
0
        public void CanUseSuppliedCommandFactory()
        {
            var commandFactory = new CustomFactory();

            var commandInvoker = new CommandInvoker("null", typeof(CreatedByFactory), new Settings(), commandFactory: commandFactory);

            commandInvoker.Invoke(Enumerable.Empty<Switch>(), new EnvironmentSettings());

            Assert.That(commandInvoker.CommandInstance, Is.TypeOf<CreatedByFactory>());

            var createdByFactory = (CreatedByFactory)commandInvoker.CommandInstance;
            Assert.That(createdByFactory.CtorInjectedValue, Is.EqualTo("ctor!!"));

            Assert.That(commandFactory.WasProperlyReleased, Is.True, "The created command instance was NOT properly released after use!");
        }
Пример #10
0
        public void TransactionIsRolledBackWhenExceptionOccurs()
        {
            var kernel = new StandardKernel();

            var mockCommandHandler = new Mock<ICommandHandler<string>>();
            mockCommandHandler.Setup(x => x.Handle("nothing")).Throws<Exception>();
            var mockSession = new Mock<ISession>();
            var mockTransaction = new Mock<ITransaction>();
            mockSession.Setup(x => x.BeginTransaction()).Returns(mockTransaction.Object);
            kernel.Bind<ICommandHandler<string>>().ToConstant(mockCommandHandler.Object);

            var commandInvoker = new CommandInvoker(kernel, mockSession.Object);
            commandInvoker.Execute("nothing");

            mockTransaction.Verify(x => x.Rollback(), Times.Once());
        }
Пример #11
0
        static void Main(string[] args)
        {
            // initialize variable
            Lamp lamp = new Lamp();
            List<ICommand<Lamp>> commands = new List<ICommand<Lamp>>();
            CommandInvoker<Lamp> invoker = new CommandInvoker<Lamp>();

            // initialize call commands
            commands.Add(new SwitchOnLampCommand());
            commands.Add(new SwitchOnLampCommand());
            commands.Add(new SwitchOffLampCommand());
            commands.Add(new SwitchOnLampCommand());
            commands.Add(new SwitchOffLampCommand());
            commands.Add(new SwitchOnLampCommand());

            // call commands from invoker
            invoker.InvokeAll(commands, lamp);
        }
Пример #12
0
        public void MigrateEngine() {
            try {
                MakeTestConfigFile();
                IPluginFactory factory = new PluginFactory();
                ICommandInvoker invoker = new CommandInvoker(factory);
                IDbDeliveryEngine engine = new DbDeliveryEngine(factory, invoker);
                engine.Init();
                engine.Migrate("DbDelivery", "test");

                Assert.IsTrue(File.Exists("test_file2.txt"));
                string content = File.ReadAllText("test_file2.txt");
                Assert.AreEqual("TEST_MESSAGE_2", content);

            } finally {
                if (File.Exists("config.xml")) {
                    File.Delete("config.xml");
                }
                if (File.Exists("test_file2.txt")) {
                    File.Delete("test_file2.txt");
                }
            }
        }
Пример #13
0
        // GET: Bike
        public ActionResult Index(string SearchRegNumber, string SearchProducer, string SearchColour, int?id)
        {
            //call BL
            BikeSearchCommand _command = new BikeSearchCommand();

            _command.RegNumber = SearchRegNumber;
            _command.Producer  = SearchProducer;
            _command.Colour    = SearchColour;
            _command.PageSize  = 3;
            _command.PageIndex = (id ?? 0);
            BikeSearchResult _result = CommandInvoker.InvokeCommand <BikeSearchCommand, BikeSearchResult>(_command);

            //

            ViewBag.HasNext     = _result.HasNext;
            ViewBag.HasPrevious = _result.HasPrevious;
            ViewBag.PageIndex   = _command.PageIndex;

            return(View(_result.Result));

            return(View());
        }
Пример #14
0
        public int Run(IRDMPPlatformRepositoryServiceLocator repositoryLocator, IDataLoadEventListener listener,
                       ICheckNotifier checkNotifier, GracefulCancellationToken token)
        {
            _input    = new ConsoleInputManager(repositoryLocator, checkNotifier);
            _listener = listener;
            _invoker  = new CommandInvoker(_input);
            _invoker.CommandImpossible += (s, c) => Console.WriteLine($"Command Impossible:{c.Command.ReasonCommandImpossible}");
            _invoker.CommandCompleted  += (s, c) => Console.WriteLine("Command Completed");

            _commands = _invoker.GetSupportedCommands().ToDictionary(
                k => BasicCommandExecution.GetCommandName(k.Name),
                v => v, StringComparer.CurrentCultureIgnoreCase);

            _picker =
                _options.CommandArgs != null && _options.CommandArgs.Any() ?
                new CommandLineObjectPicker(_options.CommandArgs, repositoryLocator) :
                null;

            if (!string.IsNullOrWhiteSpace(_options.File) && _options.Script == null)
            {
                throw new Exception("Command line option File was provided but Script property was null.  The host API failed to deserialize the file or correctly use the ExecuteCommandOptions class");
            }

            if (_options.Script != null)
            {
                RunScript(_options.Script, repositoryLocator);
            }
            else
            if (string.IsNullOrWhiteSpace(_options.CommandName))
            {
                RunCommandExecutionLoop(repositoryLocator);
            }
            else
            {
                RunCommand(_options.CommandName);
            }

            return(0);
        }
Пример #15
0
        public void Set_Rover_As_Receiver_Given_A_RoverMoveCommand()
        {
            var expectedRover          = new Mock <IRover>();
            var expectedLandingSurface = new Mock <ILandingSurface>();

            var mockRoverMoveCommand = new Mock <IRoverMoveCommand>();

            mockRoverMoveCommand.Setup(x => x.GetCommandType()).Returns(CommandType.RoverMoveCommand);

            var commandInvoker = new CommandInvoker(null);

            commandInvoker.Assign(new[] { mockRoverMoveCommand.Object });
            commandInvoker.SetLandingSurface(expectedLandingSurface.Object);
            commandInvoker.SetRovers(new List <IRover> {
                null, expectedRover.Object
            });

            commandInvoker.InvokeAll();

            mockRoverMoveCommand.Verify(
                x => x.SetReceiver(expectedRover.Object, expectedLandingSurface.Object), Times.Once());
        }
Пример #16
0
        private void HandleObjectPlacement()
        {
            RaycastHit   hitInfo;
            Ray          rayHover = _camera.ScreenPointToRay(Input.mousePosition);
            GridPosition selectedObjectGridPosition;

            if (Physics.Raycast(rayHover, out hitInfo))
            {
                selectedObjectGridPosition = _grid.GetNearestPointOnGrid(hitInfo.point);
                _isPositionValid           = _grid.CheckIfGridPositionIsValid(selectedObjectGridPosition);

                _selectedObject.transform.position = selectedObjectGridPosition.Position;
                _selectedObject.SetVisability(_isPositionValid);

                if (Input.GetMouseButtonDown(0))
                {
                    if (_isPositionValid)
                    {
                        ICommand command = new PlaceLevelObjectCommand(_objectToPlace, selectedObjectGridPosition, _grid);
                        CommandInvoker.AddCommand(command);
                    }
                }

                if (Input.GetMouseButtonDown(1))
                {
                    LevelObject objectToDelete = hitInfo.collider.transform.GetComponent <LevelObject>();
                    if (objectToDelete != null)
                    {
                        ICommand command = new DeleteLevelObjectCommand(
                            objectToDelete,
                            _grid.GetNearestPointOnGrid(objectToDelete.transform.position),
                            _grid);

                        CommandInvoker.AddCommand(command);
                    }
                }
            }
        }
        public ActionResult Invoke(string command)
        {
            // Convert "GET /Users" to GetUsers:
            command = BuildFullCommandName(command);

            // Find the appropriate command type, eg ClientCommanding.Commands.GetUsers
            var commandType = Type.GetType("ClientCommanding.Commands." + command);

            // Ensure it's a valid comand
            if (commandType == null) {
                throw new HttpException(404, "Command Not found");
            }

            var commandInstance = Activator.CreateInstance(commandType);

            // Bind request params to the command instance.
            BindCommandProperties(commandType, commandInstance);

            var invoker = new CommandInvoker();
            var result = invoker.InvokeCommand(commandInstance, commandType);

            return result;
        }
Пример #18
0
        public void TestAdd()
        {
            var invoker = new CommandInvoker();
            var result  = new ResultReceiver();

            var numbers = new List <Number>
            {
                new Number {
                    EnteredNumber = 1, IsCalculated = false
                },
                new Number {
                    EnteredNumber = 2, IsCalculated = false
                },
                new Number {
                    EnteredNumber = 3, IsCalculated = false
                }
            };

            invoker.IncludeOperations(new AddCommand(result, numbers));
            invoker.CalculatingOperations();

            Assert.AreEqual(6.0, result.Answer);
        }
Пример #19
0
        public void Create_RetainUserNewCommand_Test()
        {
            var userCommandsFile = Path.GetTempFileName();

            File.Delete(userCommandsFile);
            var userCommands = new SerializedCommands()
            {
                // Version = ...,
                commandArray = new Command[]
                {
                    new SendMessageCommand("class", "window", 0, 0, 0)
                    {
                        Cmd = "userCmd"
                    }
                }
            };

            SerializedCommands.SaveCommands(userCommandsFile, userCommands, "0.0.0.0");

            var commands = CommandInvoker.Create(userCommandsFile, "0.0.0.0", false);

            Assert.NotEmpty(commands.Values.Cast <Command>().Where(cmd => cmd.Cmd.Equals("userCmd")));
        }
    public override void StartExecution(Action <Command> OnCommandFinished)
    {
        base.StartExecution(OnCommandFinished);
        invoker = new CommandInvoker(OnStageStarted, OnStageFinished, null);

        bool loadFromSave = PhotonNetwork.CurrentRoom.CustomProperties.ContainsKey("loadSavedGame") && (bool)PhotonNetwork.CurrentRoom.CustomProperties["loadSavedGame"];

        if (GameplayController.instance.session.roomOwner.IsLocal && loadFromSave)
        {
            Action switchLoadSaveState = delegate
            {
                Hashtable table = new Hashtable();
                table.Add("loadSavedGame", false);
                PhotonNetwork.CurrentRoom.SetCustomProperties(table);
            };

            invoker = new CommandInvoker(OnStageStarted, OnStageFinished, switchLoadSaveState);
            GameSave save = new GameSave();

            string fileName = (string)PhotonNetwork.CurrentRoom.CustomProperties["saveFileName"];
            FileManager.LoadGame(ref save, fileName);

            Command loadSaveSession = new ActionCommand(
                "LoadSaveSession",
                delegate { GameplayController.instance.session.LoadFromSave(ref save); }
                );
            Command loadSaveBoard = new ActionCommand(
                "LoadSaveBoard",
                delegate { GameplayController.instance.board.LoadFromSave(ref save); }
                );

            invoker.AddCommand(loadSaveSession);
            invoker.AddCommand(loadSaveBoard);
        }

        invoker.Start();
    }
Пример #21
0
        public static bool TryGetDevice(SerialPort Port, out IEsp8266Device Device)
        {
            Device = null;

            #region Error checking
            if (Port == null)
            {
                return(false);
            }

            if (!Port.IsOpen)
            {
                try {
                    Port.Open();
                }
                catch (UnauthorizedAccessException e) {
                    return(false);
                }
            }
            #endregion

            StreamWriter sw = new StreamWriter(Port.BaseStream)
            {
                AutoFlush = true
            };
            StreamReader sr = new StreamReader(Port.BaseStream);

            CommandInvoker c        = new CommandInvoker(sr, sw);
            DeviceResponse Response = c.Send("AT");

            if (Response.RequestSucceeded)
            {
                Device = new BasicEspDevice(c);
            }

            return(Response.RequestSucceeded);
        }
Пример #22
0
        public void TestAddAndSub()
        {
            var invoker = new CommandInvoker();
            var result  = new ResultReceiver();

            var addNumbers = new List <Number>
            {
                new Number {
                    EnteredNumber = 1, IsCalculated = false
                },
                new Number {
                    EnteredNumber = 2, IsCalculated = false
                }
            };
            var addCommand = new AddCommand(result, addNumbers);

            invoker.IncludeOperations(addCommand);
            invoker.CalculatingOperations();

            Assert.AreEqual(3.0, result.Answer);
            invoker.RemoveOperation(addCommand);


            var subNumbers = new List <Number>
            {
                new Number {
                    EnteredNumber = 3, IsCalculated = false
                }
            };

            invoker.IncludeOperations(new SubtractCommand(result, subNumbers));
            invoker.CalculatingOperations();

            Assert.AreEqual(0.0, result.Answer);
            invoker.RemoveOperation(addCommand);
        }
Пример #23
0
        public void CommandInvokerCustomParser()
        {
            var inv = new CommandInvoker();

            inv.Register("abc", (NnN v) => v.A + v.B);

            for (var i = 0; i < Times; ++i)
            {
                int ra = _rand.Next(0, 1024), rb = _rand.Next(0, 1024);
                Trace.WriteLine($"Test with ra = {ra}, rb = {rb}");
                Assert.AreEqual(inv.Invoke("abc", $"{ra}:{rb}"), ra + rb);
            }

            inv.CustomParser(typeof(NnN), str => int.TryParse(str, out var v) ? new NnN {
                A = v, B = 100
            } : throw new Exception());

            for (var i = 0; i < Times; ++i)
            {
                var r = _rand.Next(0, 1024);
                Trace.WriteLine($"Test with r = {r}");
                Assert.AreEqual(inv.Invoke("abc", $"{r}"), r + 100);
            }
        }
Пример #24
0
        public RunUI(IActivateItems activator) : base(activator)
        {
            InitializeComponent();

            _commandsDictionary = new Dictionary <string, Type>(StringComparer.CurrentCultureIgnoreCase);

            _commandCaller = new CommandInvoker(activator);
            _commandCaller.CommandImpossible += (s, e) => MessageBox.Show(e.Command.ReasonCommandImpossible);
            _commandCaller.CommandCompleted  += (s, e) => this.Close();

            var commands = _commandCaller.GetSupportedCommands();

            foreach (var c in commands)
            {
                var name = BasicCommandExecution.GetCommandName(c.Name);

                if (!_commandsDictionary.ContainsKey(name))
                {
                    _commandsDictionary.Add(name, c);
                }
            }

            comboBox1.Items.AddRange(_commandsDictionary.Keys.ToArray());
        }
Пример #25
0
 public SettingsViewModel(MainViewModel viewModel)
 {
     commandInvoker = new CommandInvoker <BaseCommand>();
     mainViewModel  = viewModel;
 }
Пример #26
0
 public CommandStrategy(SnapViewDirector svd)
 {
     invoker  = new CommandInvoker(svd);
     receiver = svd;
 }
Пример #27
0
 public override void Invoke(CommandInvoker invoker, CommandArgs args)
 {
     if (args.IsEmpty())
     {
         foreach (Command c in invoker.GetCommands())
         {
             Console.WriteLine($"{c.Name()}: {c.Description()}");
         }
     }
     else
     {
         if (args.StartsWithSwitch("l"))
         {
             //Format
             int    cnt    = 0;
             string x      = "";
             string output = "";
             foreach (Command c in invoker.GetCommands())
             {
                 cnt++;
                 if (cnt == 5)
                 {
                     if (output == "" || output == null)
                     {
                         output = x;
                     }
                     else
                     {
                         output += $"\n{x}";
                     }
                     x   = "";
                     cnt = 0;
                 }
                 else
                 {
                     if (x == "" || x == null)
                     {
                         x = $"{c.Name()}";
                     }
                     else
                     {
                         x += $", {c.Name()}";
                     }
                 }
             }
         }
         else
         {
             var cmd = invoker.GetCommand(args.GetArgAtPosition(0));
             if (cmd == null)
             {
                 foreach (Command c in invoker.GetCommands())
                 {
                     Console.WriteLine($"{c.Name()}: {c.Description()}");
                 }
             }
             else
             {
                 string x = $"[]==========|COMMAND HELP|==========[]\n" +
                            $"Name: {cmd.Name()}\n" +
                            $"Description: {cmd.Description()}\n" +
                            $"Syntax: {cmd.Syntax()}\n" +
                            $"Aliases: {ToString(cmd.Aliases())}\n" +
                            $"Version: {cmd.Version()}" +
                            $"[]==========|COMMAND HELP|==========[]";
             }
         }
     }
 }
Пример #28
0
 public override void OnInvoke(CommandInvoker invoker, CommandArguments args)
 {
     Console.Clear();
 }
Пример #29
0
 public override void OnInvoke(CommandInvoker invoker, CommandArguments args)
 {
     invoker.GetProcessor().ExitProcessor(); //Terminates the current processor.
 }
Пример #30
0
 public CommandLoad()
 {
     this.invoker = CommandInvoker.GetInstance();
 }
Пример #31
0
    public void OpenCloseInventoryCanvas()
    {
        CommandInvoker OpenClose = new CommandInvoker();

        OpenClose.OpenCloseCanvas(inventoryCanvas, state);
    }
Пример #32
0
    public void OpenCloseEnergyCanvas()
    {
        CommandInvoker OpenClose = new CommandInvoker();

        OpenClose.OpenCloseCanvas(energyCanvas, state);
    }
Пример #33
0
    public void CloseShopCanvas()
    {
        CommandInvoker OpenClose = new CommandInvoker();

        OpenClose.OpenCloseCanvas(shopCanvas, state);
    }
Пример #34
0
    public void OpenSelancerCanvas()
    {
        CommandInvoker OpenClose = new CommandInvoker();

        OpenClose.OpenCloseCanvas(selancerCanvas, state);
    }
Пример #35
0
 public override void OnInvoke(CommandInvoker invoker, CommandArguments args)
 {
     //Check if the argument array is empty.
     if (args.IsEmpty())
     {
         string s = "";
         //Then display commands normally.
         foreach (Command c in invoker.GetCommands().ToArray())
         {
             if (s == "" || s == null)
             {
                 s = $"{c.CommandName()}: {c.CommandDescription()}";
             }
             else
             {
                 s += $"\n{c.CommandName()}: {c.CommandDescription()}";
             }
         }
         Console.WriteLine(s);
     }
     else if (args.GetArgumentAtPosition(0) == "-l" || args.GetArgumentAtPosition(0) == "--list")
     {
         //Display a sorted or organized list.
         string s   = "";
         int    cnt = 1;
         string ln  = "";
         foreach (Command c in invoker.GetCommands().ToArray())
         {
             if (cnt == 5)
             {
                 if (s == "" || s == null)
                 {
                     s   = $"{ln}";
                     ln  = $"{c.CommandName()}";
                     cnt = 1;
                 }
                 else
                 {
                     s  += $"\n{ln}";
                     ln  = $"{c.CommandName()}";
                     cnt = 1;
                 }
             }
             else
             {
                 if (ln == "" || ln == null)
                 {
                     ln = $"{c.CommandName()}";
                 }
                 else
                 {
                     ln += $", {c.CommandName()}";
                 }
                 cnt++;
             }
         }
         Console.WriteLine(s);
     }
     else
     {
         //Display information about a specific command or it's alias.
         var cmd = invoker.GetCommand(args.GetArgumentAtPosition(0));
         if (cmd != null)
         {
             Console.WriteLine(
                 $"==========|HELP|==========\n" +
                 $"Name: {cmd.CommandName()}\n" +
                 $"Description: {cmd.CommandDescription()}\n" +
                 $"Version: {cmd.CommandVersion()}\n" +
                 $"Copyright: {cmd.CommandCopyright()}\n" +
                 $"Aliases: {cmd.CommandAliases().ToString(' ')}\n" +
                 $"==========|HELP|=========="
                 );
         }
         else
         {
             string s = "";
             //Then display commands normally.
             foreach (Command c in invoker.GetCommands().ToArray())
             {
                 if (s == "" || s == null)
                 {
                     s = $"{c.CommandName()}: {c.CommandDescription()}";
                 }
                 else
                 {
                     s += $"\n{c.CommandName()}: {c.CommandDescription()}";
                 }
             }
             Console.WriteLine(s);
         }
     }
 }
Пример #36
0
 public CommandController(CommandInvoker commandInvoker)
 {
     _commandInvoker = commandInvoker;
 }
Пример #37
0
 public void TestInvokeCommand()
 {
     var invoker = new CommandInvoker<TestCommand>();
     Assert.AreEqual(123, invoker.Invoke(new object[] { "argument" }));
     Assert.AreEqual("argument", invoker.Instance.Parameter);
 }
Пример #38
0
 internal BasicEspDevice(CommandInvoker Command)
 {
     this.Command = Command;
 }
Пример #39
0
    void MouseInput()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (selected != null)
            {
                ResetCard(selected);
            }
            //get origin mouse position for drag calculation
            mousePosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f));
            RaycastHit2D hit = Physics2D.Raycast(mousePosition, Vector2.zero);
            if (hit)
            {
                if (hit.collider.CompareTag("Card"))
                {
                    Card(hit.collider.gameObject);
                }
                if (hit.collider.CompareTag("Foundation"))
                {
                    selected = null;
                }
            }
            else
            {
                selected = null;
            }
        }

        //when dragging, card moves with mouse
        if (Input.GetMouseButton(0))
        {
            float deltaX = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f)).x - mousePosition.x;
            float deltaY = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f)).y - mousePosition.y;

            if (selected != null)
            {
                selected.transform.position = new Vector3(originPosition.x + deltaX, originPosition.y + deltaY, -0.35f);
            }
        }

        if (Input.GetMouseButtonUp(0))
        {
            if (selected != null && selected.transform.position != originPosition)
            {
                Debug.Log("mouse up");
                mousePosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f));
                RaycastHit2D hit = Physics2D.Raycast(mousePosition, Vector2.zero);
                if (hit)
                {
                    //when card drag to another card
                    if (hit.collider.CompareTag("Card"))
                    {
                        Debug.Log(hit.collider.name);
                        if (Stackable(selected, hit.collider.gameObject))
                        {
                            ICommand command = new StackCommand(selected, hit.collider.gameObject, originPosition);
                            CommandInvoker.AddCommand(command);
                            CardColorWhite(selected);
                            selected.layer = 0;
                            selected       = null;
                        }
                    }
                    //when card drag to foundation area
                    if (hit.collider.CompareTag("Foundation"))
                    {
                        int foundationIndx = solitaire.IntoAllFoundations(selected);
                        if (foundationIndx == -1)
                        {
                            ResetCard(selected);
                        }
                        else
                        {
                            ICommand command = new FoundationCommand(selected, originPosition, foundationIndx);
                            CommandInvoker.AddCommand(command);
                        }
                        CardColorWhite(selected);
                        selected = null;
                    }
                    //when card drag to an empty cascade
                    if (hit.collider.CompareTag("Empty Cascade"))
                    {
                        //check if the cascade is really empty
                        if (hit.collider.transform.childCount == 0)
                        {
                            ICommand command = new EmptyCascadeCommand(selected, hit.collider.gameObject, originPosition);
                            CommandInvoker.AddCommand(command);
                            CardColorWhite(selected);
                            selected.layer = 0;
                            selected       = null;
                        }
                    }
                    //when card drag to free cell
                    if (hit.collider.CompareTag("Free Cell"))
                    {
                        if (selected.transform.childCount == 0)
                        {
                            int freeCellIndx = hit.collider.transform.GetSiblingIndex();
                            if (solitaire.freeCells[freeCellIndx] == "")
                            {
                                ////remove from the free cell if the card is in it
                                ICommand command = new FreeCellCommand(freeCellIndx, selected, originPosition);
                                CommandInvoker.AddCommand(command);

                                CardColorWhite(selected);
                                selected.layer = 0;
                                selected       = null;
                            }
                        }
                    }
                }
                else
                {
                    ResetCard(selected);
                    //selected = null;
                }

                if (selected != null)
                {
                    ResetCard(selected, false);
                }
            }
        }
    }
Пример #40
0
        public WhenUserRequestsToUpdateAnExistingContactWithInvalidContact()
        {
            _contactRepository = Mock.Of<IContactRepository>();
            var countyRepository = Mock.Of<ICountyRepository>();
            Mock.Get(countyRepository)
                .Setup(q => q.GetById(1))
                .Returns(new County(1, "Merseyside"));

            var countryRepository = Mock.Of<ICountryRepository>();
            Mock.Get(countryRepository)
                .Setup(q => q.GetById(1))
                .Returns(new Country(1, "UK"));

            var commandInvoker = new CommandInvoker(new ContactService(countyRepository,
                countryRepository,
                _contactRepository,
                new ValidationService(),
                new ContactAdministrationService(countyRepository,
                    countryRepository,
                    _contactRepository)));

            Mock.Get(countyRepository).Setup(q => q.GetAll()).Returns(_counties);
            Mock.Get(countryRepository).Setup(q => q.GetAll()).Returns(_countries);

            _updateCommand = new UpdateContactCommand
            {
                Id = 1,
                FirstName = "",
                Surname = "",
                Address1 = "Address 1",
                Address2 = "Address 2",
                CountyId = 1,
                CountryId = 1,
            };
            _result = commandInvoker.Execute<UpdateContactCommand, UpdateContactQueryResult>(_updateCommand);
        }
Пример #41
0
        //TODO use autofixture for the data
        public WhenUserRequestsToSaveContact()
        {
            var contactRepository = Mock.Of<IContactRepository>();
            Mock.Get(contactRepository)
                .Setup(q => q.Save(It.IsAny<Contact>()))
                .Callback<Contact>(q => _contactCreated = q);

            var countyRepository = Mock.Of<ICountyRepository>();
            Mock.Get(countyRepository)
                .Setup(q => q.GetById(1))
                .Returns(new County(1, "Merseyside"));

            var countryRepository = Mock.Of<ICountryRepository>();
            Mock.Get(countryRepository)
                .Setup(q => q.GetById(1))
                .Returns(new Country(1, "UK"));

            var commandInvoker = new CommandInvoker(new ContactService(countyRepository,
                countryRepository,
                contactRepository,
                new ValidationService(),
                new ContactAdministrationService(countyRepository,
                    countryRepository,
                    contactRepository)));

            Mock.Get(countyRepository).Setup(q => q.GetAll()).Returns(_counties);
            Mock.Get(countryRepository).Setup(q => q.GetAll()).Returns(_countries);

            commandInvoker.Execute<CreateContactCommand, CreateContactQueryResult>(new CreateContactCommand
            {
                FirstName = "Andrew",
                Surname = "Stewart",
                Address1 = "Address 1",
                Address2 = "Address 2",
                CountyId = 1,
                CountryId = 1,
            });
        }
Пример #42
0
 public MacroRunner(MacroStore macroStore, MacroTrigger trigger, CommandInvoker commandInvoker)
 {
     this.macroStore = macroStore;
     this.trigger = trigger;
     this.commandInvoker = commandInvoker;
 }
Пример #43
0
 public virtual DxfEntity.Interactor CreateEditInteractor(
     int index,
     CommandInvoker commandInvoker)
 {
     return((DxfEntity.Interactor)null);
 }
Пример #44
0
 public override void Invoke(CommandInvoker invoker, CommandArgs args)
 {
     throw new NotImplementedException();
 }
Пример #45
0
 public SimulationRunner()
 {
     _robotWorld = new RobotWorld(5, 5);
     _invoker    = new CommandInvoker();
 }
    // Start is called before the first frame update
    void Start()
    {
        //Create a SketchWorld, many commands require a SketchWorld to be present
        SketchWorld = Instantiate(Defaults.SketchWorldPrefab).GetComponent <SketchWorld>();

        //Create a LineSketchObject
        LineSketchObject = Instantiate(Defaults.LineSketchObjectPrefab).GetComponent <LineSketchObject>();
        Invoker          = new CommandInvoker();
        Invoker.ExecuteCommand(new AddControlPointCommand(this.LineSketchObject, new Vector3(1, 2, 3)));
        Invoker.ExecuteCommand(new AddControlPointCommand(this.LineSketchObject, new Vector3(1, 4, 2)));
        Invoker.ExecuteCommand(new AddControlPointCommand(this.LineSketchObject, new Vector3(1, 5, 3)));
        Invoker.ExecuteCommand(new AddControlPointCommand(this.LineSketchObject, new Vector3(1, 5, 2)));
        Invoker.Undo();
        Invoker.Redo();

        LineBrush brush = this.LineSketchObject.GetBrush() as LineBrush;

        brush.CrossSectionVertices = CircularCrossSection.GenerateVertices(3);
        brush.CrossSectionNormals  = CircularCrossSection.GenerateVertices(3, 1);
        Invoker.ExecuteCommand(new SetBrushCommand(this.LineSketchObject, brush));
        //oder ohne Command
        //this.LineSketchObject.SetBrush(brush);
        //oder nur
        //this.LineSketchObject.SetLineCrossSection(...


        //Create a RibbonSketchObject
        RibbonSketchObject = Instantiate(Defaults.RibbonSketchObjectPrefab).GetComponent <RibbonSketchObject>();
        Invoker.ExecuteCommand(new AddPointAndRotationCommand(RibbonSketchObject, new Vector3(1, 1, 1), Quaternion.identity));
        Invoker.ExecuteCommand(new AddPointAndRotationCommand(RibbonSketchObject, new Vector3(1.5f, 1.1f, 1), Quaternion.Euler(0, 0, 0)));
        Invoker.ExecuteCommand(new AddPointAndRotationCommand(RibbonSketchObject, new Vector3(2f, 1.2f, 1), Quaternion.Euler(22, 0, 0)));
        Invoker.ExecuteCommand(new AddPointAndRotationCommand(RibbonSketchObject, new Vector3(2.5f, 1.3f, 1), Quaternion.Euler(45, 0, 0)));
        Invoker.ExecuteCommand(new AddPointAndRotationCommand(RibbonSketchObject, new Vector3(3f, 1.4f, 1), Quaternion.Euler(60, 0, 0)));

        //Create a PatchSketchObject
        PatchSketchObject       = Instantiate(Defaults.PatchSketchObjectPrefab).GetComponent <PatchSketchObject>();
        PatchSketchObject.Width = 3;
        Invoker.ExecuteCommand(new AddSegmentCommand(PatchSketchObject, new List <Vector3> {
            new Vector3(0, 0, 1), new Vector3(0, 1, 2), new Vector3(0, 0, 3)
        }));
        Invoker.ExecuteCommand(new AddSegmentCommand(PatchSketchObject, new List <Vector3> {
            new Vector3(1, 1, 1), new Vector3(1, 0, 2), new Vector3(1, 1, 3)
        }));
        Invoker.ExecuteCommand(new AddSegmentCommand(PatchSketchObject, new List <Vector3> {
            new Vector3(2, 0, 1), new Vector3(2, 1, 2), new Vector3(2, 0, 3)
        }));

        //Add the LineSketchObject to the SketchWorld
        Invoker.ExecuteCommand(new AddObjectToSketchWorldRootCommand(LineSketchObject, SketchWorld));
        //Create a SketchObjectGroup and add objects to it
        SketchObjectGroup = Instantiate(Defaults.SketchObjectGroupPrefab).GetComponent <SketchObjectGroup>();
        Invoker.ExecuteCommand(new AddToGroupCommand(SketchObjectGroup, RibbonSketchObject));
        Invoker.ExecuteCommand(new AddToGroupCommand(SketchObjectGroup, PatchSketchObject));
        //Add the SketchObjectGroup to the SketchWorld
        Invoker.ExecuteCommand(new AddObjectToSketchWorldRootCommand(SketchObjectGroup, SketchWorld));

        //Serialize the SketchWorld to a XML file
        SavePath = System.IO.Path.Combine(Application.dataPath, "YourSketch.xml");
        SketchWorld.SaveSketchWorld(SavePath);

        //Create another SketchWorld and load the serialized SketchWorld
        DeserializedSketchWorld = Instantiate(Defaults.SketchWorldPrefab).GetComponent <SketchWorld>();
        DeserializedSketchWorld.LoadSketchWorld(SavePath);
        DeserializedSketchWorld.transform.position += new Vector3(5, 0, 0);

        //Export the SketchWorld as an OBJ file
        //SketchWorld.ExportSketchWorldToDefaultPath();

        //Select the SketchObjectGroup
        SketchObjectSelection = Instantiate(Defaults.SketchObjectSelectionPrefab).GetComponent <SketchObjectSelection>();
        Invoker.ExecuteCommand(new AddToSelectionAndHighlightCommand(SketchObjectSelection, SketchObjectGroup));
        Invoker.ExecuteCommand(new ActivateSelectionCommand(SketchObjectSelection));
    }