ExecuteCommand() 공개 메소드

public ExecuteCommand ( IMessage note ) : void
note IMessage
리턴 void
        //important!!!!!!!!!!!!
        //we are sorry we didn't implement the mvvm for the main window as we should, we didn't have enough time to fix it.
        //we are aware of this mistake
        //but we implemented the mvvm for the other modules
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new ViewModels.MainWindowViewModel();

            ComunicationClient client     = ComunicationClient.GetClient(8000);
            Controller         controller = new Controller(LogModel.getModel(), SettingsModel.getModel());

            try
            {
                client.ConnectToServer();
                string[] strs = { };
                client.CommandReceived += delegate(object senderObj, CommandReceivedEventArgs args)
                {
                    App.Current.Dispatcher.Invoke((Action) delegate // <--- HERE
                    {
                        JsonCommand jCommand = args.JsonCommand;
                        controller.ExecuteCommand(jCommand.CommandID, jCommand.Args, jCommand.JsonData);
                    });
                };
                client.sendCommand((int)CommandsEnum.GetConfigCommand, strs);
                client.sendCommand((int)CommandsEnum.LogsCommand, strs);
            }
            catch
            {
                this.Background = Brushes.Gray;
                this.IsEnabled  = false;
            }
        }
예제 #2
0
 /// <summary>
 /// 执行方法
 /// 如果有控制器,则控制器执行操作,
 /// 如果操作时删除,清空选择
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ExecuteCommand(object sender, ExecutedRoutedEventArgs e)
 {
     if (Controller != null)
         Controller.ExecuteCommand(e.Command, e.Parameter);
     if (e.Command == ApplicationCommands.Delete)
         Selection.Clear();
 }
예제 #3
0
파일: Server.cs 프로젝트: MorBrisker/AP2
        public static void Main(string[] args)
        {
            IController c = new Controller();
            IModel      m = new Model(c);

            c.SetModel(m);
            c.AddCommands();

            IPEndPoint  ep       = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000);
            TcpListener listener = new TcpListener(ep);

            listener.Start();
            Console.WriteLine("Waiting for client connections...");
            TcpClient client = listener.AcceptTcpClient();

            Console.WriteLine("Client connected");
            using (NetworkStream stream = client.GetStream())
                using (BinaryReader reader = new BinaryReader(stream))
                    using (BinaryWriter writer = new BinaryWriter(stream))
                    {
                        while (true)
                        {
                            //Console.WriteLine("Waiting for a number");
                            string command = reader.ReadString();
                            //string command2 = "generate maze 5 5";
                            string result = c.ExecuteCommand(command, client);
                            //Console.WriteLine(command);
                            writer.Write(result);
                        }
                    }

            client.Close();
            listener.Stop();
        }
예제 #4
0
        public static void Main(string[] args)
        {
            // Create a random generator.
            Random random = new Random();

            // Generate a map.
            MapGenerator generator = new MapGenerator(6, 3, random);
            RoomBase     startRoom = generator.Generate();

            // Prepare the game controller.
            Controller controller = new Controller(startRoom, 100, 3);

            StringBuilder builder = new StringBuilder();

            controller.DescribeRoom(builder);
            Console.Write(builder.ToString());

            // Main game loop.
            while (!controller.HasWon)
            {
                string command = Console.ReadLine();

                command = command.Trim().ToLowerInvariant();

                builder = new StringBuilder();
                controller.ExecuteCommand(builder, command);
                Console.Write(builder.ToString());
            }

            Console.ReadLine();
        }
예제 #5
0
        private void ReloadRadars_Click(object sender, RoutedEventArgs e)
        {
            Controller.ExecuteCommand(CommandsEnum.ReloadRadars);

            BitmapImage image = Controller.GetRadar(ComboBox.SelectedItem.ToString()).GetRadarImage();

            ImageBehavior.SetAnimatedSource(RadarDisplay, null);
            ImageBehavior.SetAnimatedSource(RadarDisplay, image);
        }
예제 #6
0
파일: Engine.cs 프로젝트: kmyumyun/SoftUni
        // TODO: refactor for Problem 4
        private string InterpredCommand(string[] data, string commandName)
        {
            string result     = string.Empty;
            var    controller = new Controller(this.repository, this.unitFactory);

            var executable = controller.ExecuteCommand(data);

            string output = executable.Execute();

            return(output);
        }
예제 #7
0
파일: ControllerWrap.cs 프로젝트: CDxu/test
 static int ExecuteCommand(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         Controller obj  = (Controller)ToLua.CheckObject <Controller>(L, 1);
         IMessage   arg0 = (IMessage)ToLua.CheckObject <IMessage>(L, 2);
         obj.ExecuteCommand(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
예제 #8
0
        public void ControllerCommandUndoRedo()
        {
            //Set up the model
            Model model = new Model();

            model.SetSize(new SizeF(1000, 1000)); //Set the container size so that the shape can be moved

            //Set up the shape element
            Shape shape = new Shape();

            shape.Location = new PointF(100, 100);
            model.Shapes.Add("Shape1", shape);

            //Set up the controller
            Controller controller = new Controller(model);

            //Set up the action
            shape.ActionElement = controller.CloneElement(shape);

            //Set up the command
            TranslateCommand command = controller.CommandFactory.CreateTranslateCommand();

            command.Elements = new ElementList(true);
            command.Elements.Add(shape);
            command.Dx = 20;
            command.Dy = 30;

            //Translate the action and execute the command
            command.Translate();
            controller.ExecuteCommand(command);

            Assert.IsTrue(shape.Location == new PointF(120, 130), "Translate command not applied correctly to controller.");
            Assert.IsTrue(controller.UndoStack.Count == 1, "Controller undo stack is not correct.");

            controller.UndoCommand();

            Assert.IsTrue(shape.Location == new PointF(100, 100), "Command Undo not applied correctly to controller.");
            Assert.IsTrue(controller.RedoStack.Count == 1, "Controller redo stack is not correct.");

            controller.RedoCommand();

            Assert.IsTrue(shape.Location == new PointF(120, 130), "Translate command not redone correctly on controller.");
            Assert.IsTrue(controller.UndoStack.Count == 1, "Controller undo stack is not correct after redo.");
            Assert.IsTrue(controller.RedoStack.Count == 0, "Controller redo stack is not correct after redo.");
        }
        private void buttonSend_Click(object sender, EventArgs e)
        {
            if (Controller.Locked)
            {
                return;
            }

            if (tbSendGKode.Text.Trim() == "")
            {
                return;
            }


            Controller.Locked = true;

            Controller.ExecuteCommand(tbSendGKode.Text);

            Controller.Locked = false;

            tbSendGKode.Text = "";
        }
        private void tbSendGKode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (Controller.Locked)
                {
                    return;
                }

                if (tbSendGKode.Text.Trim() == "")
                {
                    return;
                }

                Controller.Locked = true;

                Controller.ExecuteCommand(tbSendGKode.Text);

                Controller.Locked = false;

                tbSendGKode.Text = "";
            }
        }
예제 #11
0
 /// <summary>Called when the user clicks on this menu item.</summary>
 /// <param name="controller">A controller instance.</param>
 public void Select(Controller controller)
 {
     controller.View.Menu.IsVisible = false;
     controller.ExecuteCommand("disconnect");
 }
예제 #12
0
 private void ReloadAll_Click(object sender, RoutedEventArgs e)
 {
     Controller.ExecuteCommand(CommandsEnum.ReloadAll);
 }
예제 #13
0
 private void SaveWarnings_Click(object sender, RoutedEventArgs e)
 {
     Controller.ExecuteCommand(CommandsEnum.SaveWarnings);
 }
예제 #14
0
파일: EntryPoint.cs 프로젝트: jimu/ZunTzu
        static void Main(string[] args)
        {
            // required by DirectPlay Voice
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

            // depending on the command line arguments, we launch a client or a server
            if (args.Length == 2 && args[0] == "-s")
            {
                // launch standalone server
                int port = int.Parse(args[1]);
                using (IServer server = new DXServer()) {
                    server.Start((VoiceServerMode)Settings.Default.VoiceServerMode, port);
                }
            }
            else
            {
                // configure ZunTzu to handle .ztb, .ztg and .zts files
                installFileAssociations();

                // parse command line parameters or URL parameters
                string fileToOpen = parseParameters(args);

                // launch client
                System.Windows.Forms.Application.EnableVisualStyles();
#if !DEBUG
                try {
#endif
                // retrieve user settings
                DisplayProperties displayProperties;
                displayProperties.TextureQuality             = (TextureQualityType)Settings.Default.DisplayTextureFormat;
                displayProperties.MapsAndCountersDetailLevel = (DetailLevelType)Settings.Default.DisplayMapAndCounterDetail;
                displayProperties.WaitForVerticalBlank       = Settings.Default.DisplayWaitForVerticalBlank;
                displayProperties.PreferredFullscreenMode    = Settings.Default.DisplayPreferedFullscreenMode;
                displayProperties.DiceModelsDetailLevel      = (ModelDetailType)Settings.Default.DisplayDiceModelComplexity;
                displayProperties.GameAspectRatio            = (Settings.Default.DisplayWidescreen ? AspectRatioType.SixteenToTen : AspectRatioType.FourToThree);

                AudioProperties audioProperties;
                audioProperties.MuteAll            = Settings.Default.VoiceMuteAll;
                audioProperties.MuteSoundEffects   = Settings.Default.AudioDisableSoundEffects;
                audioProperties.MuteRecording      = Settings.Default.VoiceMuteRecording;
                audioProperties.MutePlayback       = Settings.Default.VoiceMutePlayback;
                audioProperties.UseVoiceActivation = true;
                audioProperties.AdjustActivationThresholdAutomatically = false;
                audioProperties.ActivationThreshold         = Settings.Default.VoiceActivationThreshold;
                audioProperties.ActivateEchoSuppression     = Settings.Default.VoiceEchoSuppression;
                audioProperties.UseAutomaticJitterControl   = Settings.Default.VoiceAutomaticJitterControl;
                audioProperties.JitterControl               = Settings.Default.VoiceJitterBuffer;
                audioProperties.DisableAutomaticGainControl = true;
                audioProperties.DisableAutoconfiguration    = Settings.Default.VoiceDisableAudioMixerAutoconfig;
                audioProperties.MicrophoneInputLevel        = Settings.Default.VoiceMicrophoneInputLevel;

                Size windowSize = Settings.Default.DisplayWindowSize;
                System.Windows.Forms.FormWindowState windowState = (Settings.Default.DisplayMaximizeWindow ? System.Windows.Forms.FormWindowState.Maximized : System.Windows.Forms.FormWindowState.Normal);

                string playerFirstName = Settings.Default.PlayerFirstName;
                string playerLastName  = Settings.Default.PlayerLastName;
                Guid playerGuid        = Settings.Default.PlayerId;
                if (playerGuid == Guid.Empty)
                {
                    // assign a unique persistent id to this player
                    do
                    {
                        playerGuid = Guid.NewGuid();
                    } while(playerGuid == Guid.Empty);
                    Settings.Default.PlayerId = playerGuid;
                    Settings.Default.Save();
                }

                if (Settings.Default.Language != "")
                {
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(Settings.Default.Language);
                }

                // initialize mainForm, model, view, controller
                using (MainForm mainForm = new MainForm(windowSize, windowState)) {
                    IModel          model          = new Model(mainForm, audioProperties, playerFirstName, playerLastName, playerGuid);
                    IView           view           = new View(model, mainForm, displayProperties);
                    IController     controller     = new Controller(model, mainForm, view);
                    IPrecisionTimer precisionTimer = new PrecisionTimer();

                    model.OpenGameBox(model.GameLibrary.DefaultGameBox);
                    model.CurrentGameBox.OpenBuiltInScenario(model.CurrentGameBox.StartupScenarioFileName);

                    view.ResetGraphicsElements();

                    if (controller.AutosaveAvailable &&
                        System.Windows.Forms.MessageBox.Show(
                            Resources.AutosaveDialogText,
                            Resources.AutosaveDialogCaption,
                            System.Windows.Forms.MessageBoxButtons.YesNoCancel,
                            System.Windows.Forms.MessageBoxIcon.Question,
                            System.Windows.Forms.MessageBoxDefaultButton.Button1)
                        == System.Windows.Forms.DialogResult.Yes)
                    {
                        mainForm.Show();
                        controller.ExecuteCommand("restoreautosave");
                    }
                    else
                    {
                        mainForm.Show();

                        if (fileToOpen != null)
                        {
                            controller.ExecuteCommand("open " + fileToOpen);
                        }
                        else
                        {
                            view.Prompter.AddTextToHistory(0xFF00FFFF, Resources.Welcome);
                        }
                    }

                    // While the form is still valid, render and process messages
                    long currentTimeInMicroseconds = precisionTimer.NowInMicroseconds;
                    while (mainForm.Created)
                    {
                        view.Render(currentTimeInMicroseconds);
                        currentTimeInMicroseconds = precisionTimer.NowInMicroseconds;
                        model.AnimationManager.Animate(currentTimeInMicroseconds);
                        controller.DoEvents(currentTimeInMicroseconds);
                    }
                }
#if !DEBUG
            } catch (Exception e) {
                // display error message, invite to send a report
                try {
                    string version = "unknown";
                    if (ApplicationDeployment.IsNetworkDeployed)
                    {
                        version = ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
                    }
                    string reportContent = e.ToString();

                    // Direct3D drivers?
                    if (reportContent.Contains("-2146232832") && reportContent.Contains("Microsoft.DirectX.Direct3D.Manager.GetDeviceCaps"))
                    {
                        System.Windows.Forms.MessageBox.Show(
                            "Graphics card doesn't meet ZunTzu's minimum requirements. Are the drivers installed?",
                            "Can't start ZunTzu",
                            System.Windows.Forms.MessageBoxButtons.OK,
                            System.Windows.Forms.MessageBoxIcon.Error);
                    }
                    else
                    {
                        ErrorForm errorForm = new ErrorForm(
                            "version " + version + "\r\n" +
                            "os " + Environment.OSVersion.VersionString + "\r\n" +
                            "framework " + Environment.Version.ToString() + "\r\n" +
                            "cpu count " + Environment.ProcessorCount.ToString() + "\r\n" +
                            reportContent);
                        errorForm.ShowDialog();
                        if (errorForm.DialogResult == System.Windows.Forms.DialogResult.OK)
                        {
                            // send an error report to www.zuntzu.com
                            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://www.zuntzu.com/forum/reportcrash.php");
                            request.UserAgent   = "ZunTzu";
                            request.Method      = "POST";
                            request.ContentType = "application/x-www-form-urlencoded";
                            Encoding encoding   = Encoding.GetEncoding(1252);
                            byte[]   reportData = encoding.GetBytes("message=" +
                                                                    HttpUtility.UrlEncode(
                                                                        "version " + version + "\r\n" +
                                                                        "os " + Environment.OSVersion.VersionString + "\r\n" +
                                                                        "framework " + Environment.Version.ToString() + "\r\n" +
                                                                        "cpu count " + Environment.ProcessorCount.ToString() + "\r\n" +
                                                                        "[code]" + reportContent + "[/code]",
                                                                        encoding));
                            request.ContentLength = reportData.Length;
                            using (Stream requestStream = request.GetRequestStream()) {
                                requestStream.Write(reportData, 0, reportData.Length);
                            }
                            request.Timeout = 20000;
                            WebResponse response = request.GetResponse();
                        }
                    }
                } catch (Exception) { }
            }
#endif
            }
        }
예제 #15
0
 private void HandleOnTriggerEvent(IEvent evt)
 {
     Controller.ExecuteCommand(evt);
     ViewManager.NotifyViews(evt);
 }
예제 #16
0
 private void ReloadWarnings_Click(object sender, RoutedEventArgs e)
 {
     Controller.ExecuteCommand(CommandsEnum.ReloadWarnings);
     SetWarnings(CbxWarningLocation.SelectedItem.ToString());
 }
        // поток выполняющий сканирование
        private void DoWork(object data)
        {
            _ThreadDoWorks = true;
            _ScanningNow   = true;

            //текущие координаты сканирования
            int _indexScanX = 0;
            int _indexScanY = 0;

            while (_ScanningNow && _ThreadDoWorks)  //цикл работает пока не прийдет команда внеплановой остановки, или не бутет выполнено всё сканирование
            {
                // 1) получаем координаты
                SurfacePoint mp = ScanSurface.Matrix[_indexScanX, _indexScanY];

                //Дальше не двигаемся, т.к. контроллер занят какой-то другой задачей
                if (Controller.Locked)
                {
                    continue;
                }

                // подходим к точке сканирования
                Controller.Locked = true;
                Controller.ExecuteCommand(@"G0 F" + numSpeedMove.Value +
                                          " X" + mp.PosX.ToString("###0,###") +
                                          " Y" + mp.PosY.ToString("###0,###") +
                                          " Z" + numZforStart.Value.ToString("###0,###"));
                Controller.Locked = false;

                // ждем завершения движения
                //WaitStop();

                Thread.Sleep(500); //задержка небольшая, что-бы станок успел разогнаться
                while (Controller.INFO.shpindel_MoveSpeed != 0)
                {
                    Thread.Sleep(100);
                }

                //запускаем сканирование, с остановкой при касании
                Controller.SendBinaryData(BinaryData.pack_C0(0x01));                       //вкл
                Controller.SendBinaryData(BinaryData.pack_D2((int)numSpeedScan.Value, 0)); // + настройка отхода, и скорости
                Controller.SendBinaryData(BinaryData.pack_C0(0x00));                       //выкл

                //WaitStop(); //ждем остановки

                Thread.Sleep(1000); //задержка небольшая, что-бы станок успел разогнаться
                while (Controller.INFO.shpindel_MoveSpeed != 0)
                {
                    Thread.Sleep(100);
                }

                //фиксируем точку
                mp.PosZ = (float)Controller.INFO.AxesZ_PositionMM;

                // установим флаг что можно обновлять таблицу на форме
                _refreshDataFromMatrix = true;

                // 2) поднимаемся обратно
                Controller.SendBinaryData(BinaryData.pack_C0(0x01));                                     //вкл
                Controller.SendBinaryData(BinaryData.pack_D2((int)numSpeedScan.Value, numReturn.Value)); // + настройка отхода, и скорости
                Controller.SendBinaryData(BinaryData.pack_C0(0x00));                                     //выкл

                WaitStop();                                                                              //ждем остановки

                // 2) перемещаемся к новой точке
                if (_indexScanX == ScanSurface.CountPointX - 1)
                {
                    // 3) проверяем что не дошли до конца массива
                    if (_indexScanY == ScanSurface.CountPointY - 1)
                    {
                        _ThreadDoWorks = false;
                    }
                    else
                    {
                        _indexScanX = 0;
                        _indexScanY++;
                    }
                }
                else
                {
                    _indexScanX++;
                }
            }
            // Поток завершен
            _ThreadDoWorks = false;
            _ScanningNow   = false;
        }
예제 #18
0
 public void SendMessageCommand(string name, object body = null)
 {
     _controller.ExecuteCommand(new Notification(name, body));
 }